2014-03-29 27 views
0

我想在IN條件的過程中使用多個輸入。我怎樣才能做到這一點?IN條件SQL Server中的問題

以下是我的查詢代碼。

Declare @iM_ID varchar(100) 
set @iM_ID='20,22,24,25' 
select @iM_ID 
SELECT M.M_ID,  
SUM(CASE WHEN CT_ID=1  
     THEN 1 
     ELSE 0 END) AS "Secret_Coupons",  
SUM(CASE WHEN CT_ID=2  
     THEN 1 
     ELSE 0 END) AS "Hot_Coupons"  
FROM C_Master  
INNER JOIN M_Master  
    ON C_Master.M_ID=M_Master.M_ID 
    and datediff(hh,getutcdate(),End_Datetime)>0 
    and M_Master.M_ID in (@iM_ID) 
GROUP BY M_Master.M_ID  
+0

它給轉換 「轉換VARCHAR值'20,22,24,25' 到的數據類型爲int時轉換失敗。」 – KSB

+1

你基本上要求('20,22,24,25')中的SQL Server'M_Master.M_ID'而不是'(20,22,24,25)'中的'M_Master.M_ID' –

回答

1

嘗試這樣

DECLARE @sql AS VARCHAR(MAX) 
Declare @iM_ID varchar(100) 
SET @iM_ID='20,22,24,25' 

SET @sql = 'SELECT M.M_ID,SUM(CASE WHEN CT_ID=1 THEN 1 ELSE 0 END) AS "Secret_Coupons",  
          SUM(CASE WHEN CT_ID=2 THEN 1 ELSE 0 END) AS "Hot_Coupons"  
      FROM C_Master INNER JOIN M_Master ON C_Master.M_ID=M_Master.M_ID 
          AND datediff(hh,getutcdate(),End_Datetime)>0 AND 
      M_Master.M_ID IN (' + @iM_ID + ') 
GROUP BY M_Master.M_ID'  

EXECUTE @sql 
+0

即使添加@iM_ID declare並設置到您的代碼,我得到一個錯誤 - 名稱 - 您的代碼在這裏 - 不是一個有效的標識符。 –

+0

@BoratSagdiyev當你沒有他的表結構時,你怎麼會得到錯誤 –

+0

是的,我希望有一個沒有表存在的錯誤。所以'不是有效的標識符'意味着對象不存在? –