SQL Server设置变量以选择由逗号分隔的语句结果

时间:2015-02-08 13:40:43

标签: sql sql-server variables

我有这个查询,我正在尝试运行问题是SET @string =(选择语句)

DECLARE @startdate DATE
DECLARE @enddate DATE
DECLARE @string INT

SET @startdate = '1/1/2015'
SET @enddate = ' 1/31/2015 23 : 59 : 59 '
SET @string = (
        SELECT String
        FROM mytable2
        WHERE mt2.DATE BETWEEN @startdate
                AND @enddate
        )

SELECT *
FROM mytable MT WITH (NOLOCK)
INNER JOIN mytable2 MT2 WITH (NOLOCK) ON MT.ID = MT2.ID
WHERE MT.DATE BETWEEN @startdate
        AND @enddate
    AND MT2.String IN (@String)

任何帮助将不胜感激。已更新至正确的查询。

3 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望@string是来自特定查询的String列值的逗号分隔列表。如果是这样,试试这个:

DECLARE @string VARCHAR(max) = '';

SELECT @string = @string + String + ','
FROM mytable2
WHERE mt2.DATE BETWEEN @startdate AND @enddate

您最终会在字符串末尾添加一个尾随逗号。您可以使用rtrim功能将其删除。

答案 1 :(得分:0)

我建议使用XML方法进行字符串连接:

SET @string = STUFF((SELECT ',' + String
                     FROM mytable2
                     WHERE mt2.DATE BETWEEN @startdate AND @enddate
                     FOR XML PATH ('concat') TYPE
                    ).VALUE('/concat[1]', 'varchar(max)'),
                    1, 1, '')

如果你的"字符串"是其他类型,然后明确转换它:

SET @string = STUFF((SELECT ',' + cast(String as varchar(8000))
                     FROM mytable2
                     WHERE mt2.DATE BETWEEN @startdate AND @enddate
                     FOR XML PATH ('concat') TYPE
                    ).VALUE('/concat[1]', 'varchar(max)'),
                    1, 1, '')

答案 2 :(得分:0)

为什么不这样做:

DECLARE @startdate DATE
DECLARE @enddate DATE

SET @startdate = '1/1/2015'
SET @enddate = ' 1/31/2015 23 : 59 : 59 '

    SELECT 
     *
    FROM mytable MT WITH (NOLOCK)
    INNER JOIN mytable2 MT2 WITH (NOLOCK) ON MT.ID = MT2.ID
    WHERE
    MT.DATE BETWEEN @startdate AND @enddate
    AND MT2.String IN (SELECT String
                       FROM mytable2 MT2
                       WHERE MT2.DATE BETWEEN @startdate AND @enddate)