将int的csv传递给Stored proc并用于IN()

时间:2016-06-06 16:19:19

标签: sql-server

我想传递一个int

的csv
1,2,3,4,5,6,7

到存储过程,以便我可以在IN()中使用传入的值,以便

IN(1,2,3,4,5,6,7)

这甚至可能吗?

2 个答案:

答案 0 :(得分:1)

以防您只是想为SQL使用动态参数:

CREATE PROCEDURE [dbo].[takeMeAndMySeeEzzBee]
    @csv VARCHAR(30)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @sql NVARCHAR(255)
    SET @sql = 'SELECT THIS_AND_THAT FROM HERE WHERE YOU_ARE IN(' + @csv + ')'

    EXEC sp_executesql @sql
END;
GO
-- I will runawayyyy
EXEC [dbo].[takeMeAndMySeeEzzBee] @csv='1,2,3,4'

^是动态SQL如何工作的一个示例。

现在,如果您想从.csv文件中提取数据,请告诉我们;我的回答会改变。

答案 1 :(得分:0)

您可以使用XML:

CREATE PROCEDURE dbo.MyProcName
    @csv nvarchar(max)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @xml xml

    SELECT @xml = CAST('<a>' + REPLACE(@csv,',','</a><a>') +'</a>' as xml)

    SELECT what_you_need
    FROM some_table s
    INNER JOIN (
        SELECT t.v.value('.','int') as something
        FROM @xml.nodes('/a') as t(v)
        ) as p
        ON p.something = s.something
END

或者:

SELECT what_you_need
FROM some_table s
WHERE s.something IN (
    SELECT t.v.value('.','int') as something
    FROM @xml.nodes('/a') as t(v)
    )