Analytics

2015年4月30日 星期四

[MSSQL]如何 在SQL條件使用IN時傳入參數 (How to pass parameters in SQL conditions IN)


問題
如何 在SQL條件使用IN時傳入參數



解決方法
DECLARE @InConditionString VARCHAR(255)--condition
SET @InConditionString = '12345,67890'--try youself
;
WITH Split(stpos,endpos)
    AS(
        SELECT 0 AS stpos, CHARINDEX(',',@InConditionString) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(',',@InConditionString,endpos+1)
            FROM Split
            WHERE endpos > 0
    ),
    InConditionTable(seq,ColumnData)
    AS(
    SELECT 'seq' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
        'Column' = SUBSTRING(@InConditionString,stpos,COALESCE(NULLIF(endpos,0),LEN(@InConditionString)+1)-stpos)
    FROM Split
    ),
    SampleSourceTable(data)--sample source
    as(
  select '12345'
  union
  select '67890'
  union
  select '55555'
  union
  select '88888'
    )
    
    
    SELECT * FROM SampleSourceTable
    where SampleSourceTable.data in(
    select ColumnData 
    from InConditionTable)

沒有留言:

熱門文章