从多个表中插入多行 - SQL

时间:2014-10-30 08:30:27

标签: sql tsql sql-server-2012

输入参数为 - 100, 'abc,def,ghi', '10,20,30'。它们必须以

的形式插入表格中
menuid(int) cid(int) code(varchar)
----------------------------------
100         10           abc
100         20           def
100         30           ghi

我已经使用该函数从此处拆分字符串 - http://www.sqlservercentral.com/blogs/querying-microsoft-sql-server/2013/09/19/how-to-split-a-string-by-delimited-char-in-sql-server/

这是我的代码

declare @menuid int = 100
declare @strcode varchar(max)='abc,def,ghi'
declare @strid varchar(max)='10,20,30'
declare @t1 table(
menuid int,
cid int,
code varchar(100)
)
;with t1 as(
 select * from fnSplitString(@strid,',')
)
;with t2 as(
 select * from fnSplitString(@strcode,',')
)
insert into @t1 

......不知道如何从这里开始

2 个答案:

答案 0 :(得分:3)

我刚改变了用于分割和放大的功能。继续为你解决问题...

ALTER FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(id int, splitdata NVARCHAR(MAX) 
) 
BEGIN 
    DECLARE @id INT,@start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) ,@id=1

    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (id,splitdata)  
        VALUES(@id,SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @id = @id + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 
END

下一步

declare @menuid int = 100
declare @strcode varchar(max)='abc,def,ghi'
declare @strid varchar(max)='10,20,30'
declare @t1 table(
menuid int,
cid int,
code varchar(100)
)
insert into @t1 
select @menuid,
    s1.splitdata AS cid,s2.splitdata AS code
    from fnSplitString(@strid,',') s1
    INNER JOIN 
    (
        select * from fnSplitString(@strcode,',') 
    )s2 on s1.id=s2.id

select * from @t1   

答案 1 :(得分:1)

您可以更新该函数,同时为每个分割字符串返回一个数字,如下所示:

ALTER FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX), currentIndex int
) 
BEGIN 
    DECLARE @count int = 0
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata, currentIndex)  
        VALUES(SUBSTRING(@string, @start, @end - @start), @count) 
        SET @start = @end + 1 
        SET @count += 1
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 
END

现在,您可以在简单查询中加入函数的结果,并将其插入到表中。

declare @menuid int = 100
declare @strcode varchar(max)='abc,def,ghi'
declare @strid varchar(max)='10,20,30'

declare @t1 table(
menuid int,
cid int,
code varchar(100)
);


INSERT INTO @t1
 SELECT @menuid menuId, codes.splitdata cid, ids.splitdata code FROM fnSplitString(@strid,',') codes LEFT OUTER JOIN
    fnSplitString(@strcode,',') ids ON codes.currentIndex = ids.currentIndex