-1

假设我的 SP 中有三个参数。ids('1,2,3'), price('22,33.7,44'),count('4,5,1')。我也有拆分功能。现在,我想在我的数据库表中插入这些值。所以我的桌子看起来像,

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

2 回答 2

1

从 SQL 2008 开始,您可以使用表值参数- 我建议您尝试该路线,这样您就可以将结构化表传递给您的存储过程。该 MSDN 链接中有完整的示例。

我通常更喜欢该路线而不是 CSV 值/字符串拆分。我在博客上比较了一些不同的方法和性能: 表值参数 vs XML vs CSV

于 2013-02-20T14:49:09.670 回答
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'
于 2013-02-20T15:14:32.980 回答