有没有办法将在c ++中生成的数组绑定到SQL-Statement中的参数。像这样:
insert into Table1(COLUMN1, COLUMN2, COLUMN3, datum) values (:1,:2,:3,:4)
在此示例中, :1
,:2
,:3
,:4
是数组参数。
我知道Table Variable是一个非常好的主意,但我想使用另一个方法
答案 0 :(得分:1)
使用Xantos提供的建议,以分隔字符串的形式将数组传递给存储过程。然后,您可以在表值函数中使用分隔的字符串。
ALTER FUNCTION [dbo].[String_To_Int_Table]
(
@list NVARCHAR(1024)
, @delimiter NCHAR(1) = ',' --Defaults to CSV
)
RETURNS
@tableList TABLE(
value INT
)
AS
BEGIN
DECLARE @value NVARCHAR(11)
DECLARE @position INT
SET @list = LTRIM(RTRIM(@list))+ ','
SET @position = CHARINDEX(@delimiter, @list, 1)
IF REPLACE(@list, @delimiter, '') <> ''
BEGIN
WHILE @position > 0
BEGIN
SET @value = LTRIM(RTRIM(LEFT(@list, @position - 1)));
INSERT INTO @tableList (value)
VALUES (cast(@value as int));
SET @list = RIGHT(@list, LEN(@list) - @position);
SET @position = CHARINDEX(@delimiter, @list, 1);
END
END
RETURN
END
然后,您可以使用表格函数填充其他表格...
-- check to see if contacts were included...
if len(ltrim(rtrim(@Contacts)))> 0
begin
--create a temp table to hold the list of ids
CREATE TABLE #TmpContacts (ID INT);
-- use the table valued function to parse the ids into a table.
INSERT INTO #TmpContacts(ID)
SELECT Value FROM dbo.String_to_int_table(@Contacts, ',');
-- Select the @InterfaceID and the parsed ContactTypeIDs
-- for a bulk insert into the relational table...
INSERT INTO [InterfaceContacts]
([InterfaceID]
,[ContactID]
,[Created]
,[CreatedBy])
Select @InterfaceID, T.ID, CURRENT_TIMESTAMP, sUser_sName()
FROM #TmpContacts T;
drop table #TmpContacts;
end