给予字符串序列
1,2,3,4,5
和
Pen_Id=100这些标识代表颜色ID颜色为
Pen_Color
id name
1 红
2 黑
3 白
4 蓝插入数据库
Pen_Color2
格式为
id 主键
Pen_Id 已存在
Color_Id 为 1,2,3,4,5 其中1个
Color_Title 根据Color_Id查询Pen_Color的结果
该怎么做???
1,2,3,4,5
和
Pen_Id=100这些标识代表颜色ID颜色为
Pen_Color
id name
1 红
2 黑
3 白
4 蓝插入数据库
Pen_Color2
格式为
id 主键
Pen_Id 已存在
Color_Id 为 1,2,3,4,5 其中1个
Color_Title 根据Color_Id查询Pen_Color的结果
该怎么做???
然后将Color_Id ,Color_Title 插入到数据库
Pen_Color2
id Pen_Id Color_Id Color_Title
1 100 1 红
2 100 2 黑
3 100 3 白
4 100 4 蓝
-- Author : htl258(Tony)
-- Date : 2010-03-31 17:09:11
-- Version:Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (Intel X86)
-- Mar 29 2009 10:27:29
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Developer Edition on Windows NT 5.1 <X86> (Build 2600: Service Pack 2)
--------------------------------------------------------------------------
--> 生成测试数据表:Pen_Color2IF NOT OBJECT_ID('[Pen_Color2]') IS NULL
DROP TABLE [Pen_Color2]
GO
CREATE TABLE [Pen_Color2]([id] INT Identity,[Pen_Id] INT,[Color_Id] INT,[Color_Title] NVARCHAR(10))
GO
--SELECT * FROM [Pen_Color2]--> 生成测试数据表:Pen_ColorIF NOT OBJECT_ID('[Pen_Color]') IS NULL
DROP TABLE [Pen_Color]
GO
CREATE TABLE [Pen_Color]([id] INT,[name] NVARCHAR(10))
INSERT [Pen_Color]
SELECT 1,N'红' UNION ALL
SELECT 2,N'黑' UNION ALL
SELECT 3,N'白' UNION ALL
SELECT 4,N'蓝'
GO
--SELECT * FROM [Pen_Color]-->SQL查询如下:
declare @s varchar(5000),@pen_id int
set @s='1,2,3,4,5'
set @pen_id=100--开始插入数据:
insert Pen_Color2 select @pen_id,* from Pen_Color where CHARINDEX(','+ltrim(id)+',',','+@s+',')>0--查询最终结果
select * from Pen_Color2
/*
id Pen_Id Color_Id Color_Title
----------- ----------- ----------- -----------
1 100 1 红
2 100 2 黑
3 100 3 白
4 100 4 蓝(4 行受影响)
*/
insert #Pen_Color select 1 ,'红'
insert #Pen_Color select 2 ,'黑'
insert #Pen_Color select 3 ,'白'
insert #Pen_Color select 4 ,'蓝'create table #Pen_Color2(id int identity(1,1),Pen_Id int,Color_Id int,Color_Title varchar(10))create proc tes_p ( @var varchar(20),@Pen_Id int)
as
--set @var='1,2,3,4,5'
--set @Pen_Id=100
insert #Pen_Color2(Pen_Id,Color_Id,Color_Title)
select @Pen_Id,* from #Pen_Color where ','+@var+',' like '%,'+ltrim(id)+',%'
order by charindex(ltrim(id),@var)exec tes_p '1,2,3,4,5',100select * from #Pen_Color2 id Pen_Id Color_Id Color_Title
----------- ----------- ----------- -----------
1 100 1 红
2 100 2 黑
3 100 3 白
4 100 4 蓝(4 行受影响)