我想使用存储过程将批量值插入表中。
以下是名为m1
的下表,其中包含两个字段:
create table m1
(
cola varchar(50),
colb varchar(50)
);
过程m1_test
将值插入表中:
create procedure m1_test
@stringCola varchar(max),
@stringColb varchar(max)
AS
INSERT INTO m1 values(@stringCola,@stringColb);
GO
上述步骤适用于插入单个值,如下所示:
---EXECUTE SP
EXECUTE m1_test @stringCola = 'A1',@stringColb = 'Z1';
但是如果我想在单个字符串中一次插入更多的值,如下所示:
---EXECUTE SP
EXECUTE m1_test @stringCola = 'A1,A2,A3',@stringColb = 'Z1,Z2,Z3';
输出应为:
cola colb
------------
A1 Z1
A2 Z2
A3 Z3
答案 0 :(得分:1)
首先,您需要创建一个表值函数,它将以表格的形式返回逗号分隔值。
为我找到here的函数实现以下代码,稍作修改,返回一个标识列,稍后您将使用JOIN
来获取第一个值的元组对于列A和列B (A1, Z1)
的第一个值,依此类推第2个,第3个等:
CREATE FUNCTION Split (@InputString VARCHAR(8000), @Delimiter VARCHAR(50))
RETURNS @Items TABLE (ID INTEGER IDENTITY(1,1), Item VARCHAR(8000))
AS
BEGIN
IF @Delimiter = ' '
BEGIN
SET @Delimiter = ','
SET @InputString = REPLACE(@InputString, ' ', @Delimiter)
END
IF (@Delimiter IS NULL OR @Delimiter = '')
SET @Delimiter = ','
--INSERT INTO @Items VALUES (@Delimiter) -- Diagnostic
--INSERT INTO @Items VALUES (@InputString) -- Diagnostic
DECLARE @Item VARCHAR(8000)
DECLARE @ItemList VARCHAR(8000)
DECLARE @DelimIndex INT
SET @ItemList = @InputString
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
WHILE (@DelimIndex != 0)
BEGIN
SET @Item = SUBSTRING(@ItemList, 0, @DelimIndex)
INSERT INTO @Items VALUES (@Item)
-- Set @ItemList = @ItemList minus one less item
SET @ItemList = SUBSTRING(@ItemList, @DelimIndex+1, LEN(@ItemList)-@DelimIndex)
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
END -- End WHILE
IF @Item IS NOT NULL -- At least one delimiter was encountered in @InputString
BEGIN
SET @Item = @ItemList
INSERT INTO @Items VALUES (@Item)
END
-- No delimiters were encountered in @InputString, so just return @InputString
ELSE INSERT INTO @Items VALUES (@InputString)
RETURN
END -- End Function
GO
---- Set Permissions
--GRANT SELECT ON Split TO UserRole1
--GRANT SELECT ON Split TO UserRole2
--GO
现在,在创建此功能后,将存储过程修改为:
CREATE PROCEDURE m1_test @stringCola VARCHAR(max), @stringColb VARCHAR(max)
AS
INSERT INTO m1
SELECT A.Item, B.Item
FROM Split(@stringColA, ',') A
INNER JOIN Split(@stringColB, ',') B ON A.ID = B.ID
GO
答案 1 :(得分:1)
正如我在评论中所说,这是糟糕的设计,但你可以这样做:
INSERT INTO m1 values
SELECT a.d ,
b.d
FROM (SELECT Split.a.value('.', 'VARCHAR(100)') d ,
ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL ) ) rn
FROM (SELECT CAST('<M>' + REPLACE(@stringCola, ',', '</M><M>') + '</M>' AS XML) d) A
CROSS APPLY d.nodes('/M') AS Split ( a )
) a
JOIN
(SELECT Split.a.value('.', 'VARCHAR(100)') d ,
ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL ) ) rn
FROM (SELECT CAST('<M>' + REPLACE(@stringColb, ',', '</M><M>') + '</M>' AS XML) d ) A
CROSS APPLY d.nodes('/M') AS Split ( a )
) b ON a.rn = b.rn