2015-02-08 50 views
0

分隔語句結果我有這個疑問,我正在嘗試運行的問題是,SET @string =(select語句)SQL服務器設置變量來選擇用逗號

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) 

任何幫助,將不勝感激。更新爲正確的查詢。

回答

0

如果我理解正確,您希望@string是來自特定查詢的列值的逗號分隔列表。如果是這樣,請嘗試以下操作:

DECLARE @string VARCHAR(max) = ''; 

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

您將以字符串末尾的尾隨逗號結束。您可以使用rtrim功能將其關閉。

+0

我得到這個錯誤,因爲我的var是一個INT 轉換失敗轉換v archar值','爲數據類型int。 所以我需要它列出由逗號分隔的INT值 – jlusco 2015-02-08 13:56:30

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, '') 
0

爲什麼不這樣做,這way:

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)