2013-02-20 73 views
-1

假設我有三個參數在我的SP中。 Ids('1,2,3'),價格('22,33.7,44'),計數('4,5,1')。我也有拆分功能。現在,我想將這些值插入到我的數據庫表中。所以,我的表的樣子,如何將三個逗號分隔的參數放入表中?

ID Price Count 
1 22  4 
2 33.7 5 
3 44  1 

回答

1

從2008年起,SQL,您可以使用Table Valued Parameters - 我建議你嘗試這條路線,所以你可以只通過一個結構化的表格到您的存儲過程。該MSDN鏈接中有完整的示例。

我更喜歡這種路線通常通過CSV值/字符串拆分。我在這裏用一些不同的方法比較&性能:Table Valued Parameters vs XML vs CSV

+0

你能舉個例子嗎? – user960567 2013-02-20 14:53:41

+0

這兩個鏈接都有示例。在你的情況下,你只需要一個帶有3列的表格值(ID,Price,Count) – AdaTheDev 2013-02-20 14:55:35

+0

Simnply極好。爲什麼-1? – user960567 2013-02-20 15:05:13

1
create function dbo.SimpleSplit(@str varchar(max)) 
returns @table table (
    val varchar(max), 
    rowid int 
) 
with schemabinding 
as 
begin 
    declare @pos int, 
      @newPos int, 
      @rowid int; 
    set @pos = 1; 
    set @newPos = charindex(',', @str, 1); 
    set @rowid = 1; 

    while (@newPos != 0) 
    begin 
     insert into @table 
      values (substring(@str, @pos, @newPos - @pos), @rowid); 

     set @rowid += 1; 

     set @pos = @newPos + 1; 
     set @newPos = charindex(',', @str, @pos); 

     if (@newPos = 0) 
      insert into @table 
       values (substring(@str, @pos, len(@str)), @rowid); 
    end 

    return; 
end 
GO 

create procedure somesp (@id varchar(128), @price varchar(128), @count varchar(128)) 
as 
    select t.val as id, t2.val as price, t3.val as [count] 
    from dbo.SimpleSplit(@id) t 
    inner join dbo.SimpleSplit(@price) t2 on t.rowid = t2.rowid 
    inner join dbo.SimpleSplit(@count) t3 on t.rowid = t3.rowid 
GO 

exec somesp '1,2,3', '22,33.7,44', '4,5,1'