带光标的动态IN

时间:2010-12-10 17:12:15

标签: sql-server-2000

我在游标中有一个动态的in语句,并且包含一个字符串集合:

DECLARE @DBs nvarchar(4000)
    SET  @DBs="'aaa','bbb','ccc','ddd'"

DECLARE CompanyDBCursor CURSOR FOR 
  SELECT Interid 
    FROM tableName
   WHERE interid  in (@DBs)

但它出现错误 - 列名无效

1 个答案:

答案 0 :(得分:0)

试试这个:

DECLARE @DBs varchar(8000)
        SET  @DBs='aaa,bbb,ccc,ddd'


DECLARE CompanyDBCursor CURSOR FOR 
  SELECT Interid 
    FROM tableName
   WHERE interid  in (SELECT * FROM dbo.SPLIT(@DBs,','))

这是表值函数:

CREATE FUNCTION [dbo].[SPLIT] (
    @str_in VARCHAR(8000),
    @separator VARCHAR(4)
)
RETURNS @strtable TABLE (strval VARCHAR(8000))
AS
BEGIN
    DECLARE @Occurrences INT, @Counter INT, @tmpStr VARCHAR(8000)
    SET @Counter = 0
    IF SUBSTRING(@str_in,LEN(@str_in),1) <> @separator 
        SET @str_in = @str_in + @separator

    SET @Occurrences = (DATALENGTH(REPLACE(@str_in,@separator,@separator+'#')) - DATALENGTH(@str_in))/ DATALENGTH(@separator)
    SET @tmpStr = @str_in
    WHILE @Counter <= @Occurrences 
    BEGIN
        SET @Counter = @Counter + 1
        INSERT INTO @strtable VALUES ( SUBSTRING(@tmpStr,1,CHARINDEX(@separator,@tmpStr)-1))
        SET @tmpStr = SUBSTRING(@tmpStr,CHARINDEX(@separator,@tmpStr)+1,8000)
        IF DATALENGTH(@tmpStr) = 0
            BREAK
    END
    RETURN 
END