2014年1月6日 星期一

for MSSQL-- 「in 」語法後面要用字串變數去做,行嗎?

舉例:
==================================
declare @id as varchar(100)
set @id='1,150,45,33'
 select rows from table where table.id in (@id)
============================
行嗎?
以上面這寫法是不行的,不過只要變巧一下
在這之前,先準備好一個叫做SplitWords函數,放心,人家已經寫好了
為了怕連結失效,我也在此Ctl-C / Ctl-V一下
================================================
CREATE FUNCTION SplitWords(@text varchar(8000))
   RETURNS @words TABLE (
      pos smallint primary key,
      value varchar(8000)
   )
AS
BEGIN
   DECLARE
      @pos smallint,
      @i smallint,
      @j smallint,
      @s varchar(8000)

   SET @pos = 1
   WHILE @pos <= LEN(@text) 
   BEGIN 
      SET @i = CHARINDEX(' ', @text, @pos)
      SET @j = CHARINDEX(',', @text, @pos)
      IF @i > 0 OR @j > 0
      BEGIN
         IF @i = 0 OR (@j > 0 AND @j < @i)
            SET @i = @j

         IF @i > @pos
         BEGIN
            -- @i now holds the earliest delimiter in the string
            SET @s = SUBSTRING(@text, @pos, @i - @pos)

            INSERT INTO @words
            VALUES (@pos, @s)
         END 
         SET @pos = @i + 1

         WHILE @pos < LEN(@text) 
            AND SUBSTRING(@text, @pos, 1) IN (' ', ',')
            SET @pos = @pos + 1 
      END 
      ELSE 
      BEGIN 
         INSERT INTO @words 
         VALUES (@pos, SUBSTRING(@text, @pos, LEN(@text) - @pos + 1))

         SET @pos = LEN(@text) + 1 
      END 
   END 
   RETURN 
END
================================================
有這個好用的函數後,之前的
----------------------------------------------------
declare @id as varchar(100)
set @id='1,150,45,33'
 select * from table1 where table1.id in (@id)
----------------------------------------------------
 改成:
----------------------------------------------------
declare @id as varchar(100)
set @id='1,150,45,33'
 select * from table1 t1
where t1.id in (select value from  dbo.SplitWords(@id) )
----------------------------------------------------
怎樣,好用吧?