逗号分隔值到SQL IN STATEMENT

时间:2016-06-06 14:14:29

标签: sql sql-server-2008

如果我有逗号分隔的值列表:

A1,B2,B3

如何将其传递给变量,然后将其形成SQL IN语句。

DECLARE @DATE AS VARCHAR(50)

SELECT @DATE = CONVERT(VARCHAR(8), Getdate(), 112)

--PRINT @DATE
DECLARE @TIME AS VARCHAR(50)

--PRINT TIME
SELECT @TIME = Replace(CONVERT(VARCHAR(5), Getdate(), 108), ':', '')

DECLARE @ID AS VARCHAR(50)

SELECT @ID = Replace(W0128001, 32322, 32323, 3232323, 2323232, ',', ',')

--PRINT @ID
DECLARE @QUERY NVARCHAR(MAX);

SET @QUERY = 'SELECT * INTO BACKUPTABLE_' + @DATE + @TIME
             + '
FROM TABLE
WHERE ID IN (' + '''' + @ID + ''')'

--EXEC @query
PRINT @QUERY 

我试图在上面做一个替换,但我想要它,以便最终用户可以粘贴到值中,我的脚本将处理逗号并正确地形成它。它也应该从最后删除最后一个逗号。

我的输出需要阅读:

SELECT * INTO BACKUPTABLE_201606061503
FROM TABLE
WHERE ID IN ('W0128001','32322','32323','3232323','2323232')

2 个答案:

答案 0 :(得分:2)

首先,你用单引号括起来:

SET @QUERY = 'SELECT * INTO BACKUPTABLE_' + @DATE + @TIME + '
FROM TABLE
WHERE ID IN (' + @ID + ')';

还有其他方法可以将逗号分隔的值传递给SQL语句,包括使用split()函数或XML。

答案 1 :(得分:0)

CREATE PROCEDURE [dbo].[CreateBackupTable]
    @ID varchar(100) = NULL
AS
BEGIN
    SET NOCOUNT ON;

DECLARE @DATE VARCHAR(50)= CONVERT(VARCHAR(8), Getdate(), 112);
DECLARE @TIME VARCHAR(50) = Replace(CONVERT(VARCHAR(5), Getdate(), 108), ':', '')

    declare @xml xml,@SQL NVARCHAR(MAX);

    set @xml = N'<root><r>' + replace(@ID,',','</r><r>') + '</r></root>'

 SET @SQL = N' SELECT * INTO ' + QUOTENAME('BACKUPTABLE_' + @DATE + @TIME)
         +  N' from TableName '
         +  N' where ID IN (
                            select r.value(''.'',''varchar(max)'') as item
                            from @xml.nodes(''//root/r'') as records(r)
                            )' 

    exec sp_executesql @sql
                    , N'@ID varchar(100), @xml XML'
                    , @ID
                    , @Xml
END