Sql 如何将三个逗号分隔的参数放入一个表中?

Sql 如何将三个逗号分隔的参数放入一个表中?,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,假设我的SP.id('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 从SQL 2008开始,您可以使用-我建议您尝试这种方法,这样您就可以将结构化表传递到存储过程中。MSDN链接中有完整的示例 与CSV值/字符串拆分相比,我更喜欢这种路由。我在博客中比较了一些

假设我的SP.id('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

从SQL 2008开始,您可以使用-我建议您尝试这种方法,这样您就可以将结构化表传递到存储过程中。MSDN链接中有完整的示例


与CSV值/字符串拆分相比,我更喜欢这种路由。我在博客中比较了一些不同的方法和性能:

两个链接中都有示例。在您的例子中,您只需要一个具有3列(ID、Price、Count)的单表值参数
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'