变量中的单引号

时间:2015-01-23 14:45:59

标签: sql-server tsql

当我在变量中硬编码值时,知道为什么这个Select IN不起作用?

set quoted_identifier off

declare @IPAddressList   varchar(100)

Select @IPAddressList = "'108.61.51.101', '206.221.181.5'"   -- double quotes surrounding single quoted IP addresses

Select @IPAddressList  --- this shows as is:   '108.61.51.101', '206.221.181.5'

-- This returns nothing, but expect it to return rows just like the 2nd select below.
Select *
from dbo.DDoSAttacks
where TargetIP IN (@IPAddressList)

-- This does return rows as expected. 
Select *
from DDoSAttacks
where TargetIP IN ('108.61.51.101', '206.221.181.5')

set quoted_identifier on

2 个答案:

答案 0 :(得分:1)

您需要一个答案,否则人们会继续访问此问题。但Marc_S的评论很明显:

IN运算符需要一个值列表(int或字符串) - 但是如果你提供@IPAddressList varchar(100),那么你将提供一个字符串值

如果您希望它工作,您可以创建一个函数,将分隔的字符串解析为表,然后对表中的值执行“IN”。

CREATE FUNCTION [dbo].[fn_ParseDelimited] 
(
    @ParseString varchar(MAX),
    @Delimiter   varchar(10)
)
RETURNS @tbl TABLE (value varchar(MAX))
AS
BEGIN
    DECLARE @i int, @j int

    declare @lenParseString int;
    set @lenParseString = LEN(@ParseString);

    DECLARE @lenDelimiter int;  
    set @lenDelimiter = LEN(@Delimiter);

    SELECT @i = 1
    WHILE (@i <= @lenParseString)
    BEGIN
        select  @j = CHARINDEX(@Delimiter, @ParseString, @i)
        IF @j = 0
        BEGIN
            SELECT @j = @lenParseString + 1;
        END

        INSERT @tbl SELECT SUBSTRING(@ParseString, @i, @j - @i)
        SELECT @i = @j + @lenDelimiter
    END
    RETURN
END

然后你可以像这样使用你的功能:

select dd.* from 
dbo.DDosAttacks dd 
inner join dbo.fn_ParseDelimited(@IPAddressList,',') lst
on dd.TargetIP = lst.Value

答案 1 :(得分:0)

您应该使用动态SQL,如下所示:

declare @sql nvarchar(255)
select @sql='Select * from dbo.DDoSAttacks where TargetIP IN ('+@IPAddressList+')';
EXECUTE sp_executesql @sql

请参阅:dynamic sql