如何使用" IN"对SQL语句使用声明的变量条件

时间:2017-06-06 07:36:13

标签: sql-server sql-server-2014

我正在尝试编写一些代码,但它不起作用。只有那些TypeT描述。如何针对以下情况显示TypeTTypeS条件?

DECLARE @PaymentType VARCHAR(20) = '';

SELECT @PaymentType = LISTID 
FROM LIST 
WHERE LISTCONFIG IN ('TypeT', 'TypeS')

SELECT * 
FROM LIST 
WHERE LISTID IN  (@PaymentType)

4 个答案:

答案 0 :(得分:2)

尝试以下

SELECT * FROM LIST 
WHERE LISTID IN  (select LISTID FROM LIST WHERE LISTCONFIG IN 'TypeT','TypeS'))

或者您只能在sql server 2016中使用以下内容

DECLARE @PaymentType VARCHAR(20)
SELECT @PaymentType= isnull(@PaymentType+',','')+LISTID FROM list WHERE LISTID IN ('TypeT','TypeS')
SELECT * FROM LIST WHERE LISTID IN  (select value from STRING_SPLIT(@PaymentType, ',')  )

答案 1 :(得分:1)

尝试:

SELECT * 
FROM LIST 
WHERE 
    LISTID IN  (SELECT LISTID FROM LIST WHERE LISTCONFIG IN ('TypeT','TypeS'))

但是,我认为这仍然太复杂了。你试过了吗?

SELECT *
FROM LIST WHERE LISTCONFIG IN ('TypeT','TypeS')

答案 2 :(得分:1)

如果您想使用IN执行此操作,则必须使用动态SQL执行此操作。这也意味着创建逗号分隔的字符串。这是可行的,但更简单的方法是:

DECLARE @PaymentType TABLE (ListID INT) ;

INSERT @PaymentType (ListID)
SELECT LISTID FROM LIST WHERE LISTCONFIG IN ('TypeT','TypeS')

SELECT  LST.* 
FROM    LIST Lst
JOIN    @PaymentType AS PT
    ON  PT.ListID = Lst.ListID

答案 3 :(得分:1)

另一种解决方案是使用动态字符串。如果您的sql版本低于2016

DECLARE @PaymentType VARCHAR(20)
SELECT @PaymentType= isnull(@PaymentType+',','')+LISTID FROM list WHERE LISTID IN ('TypeT','TypeS')
exec('SELECT * FROM LIST WHERE LISTID IN  ('+@PaymentType+')')