Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2005 SQL Server 2005单引号字符串列表失败_Sql Server 2005_Tsql - Fatal编程技术网

Sql server 2005 SQL Server 2005单引号字符串列表失败

Sql server 2005 SQL Server 2005单引号字符串列表失败,sql-server-2005,tsql,Sql Server 2005,Tsql,我有一个SP,它有一个nvarchar(max)参数@p1。这是以逗号分隔的代码列表,例如100200300等 在SP中,我声明了一个变量@p2 nvarchar(max),并将@p1列表转换为单引号列表 set @p2 = N'''' + replace(@p1,',',''',''') + '''' 当我“选择”@p2时,将返回正确的'100',200',300' 如果我在子选择中使用@p2,例如 select x,y,z from table1 where id in (@p2) 我

我有一个SP,它有一个
nvarchar(max)
参数
@p1
。这是以逗号分隔的代码列表,例如
100200300

在SP中,我声明了一个变量
@p2 nvarchar(max)
,并将
@p1
列表转换为单引号列表

set @p2 = N'''' + replace(@p1,',',''',''') + ''''
当我“选择”
@p2
时,将返回正确的
'100',200',300'

如果我在子选择中使用
@p2
,例如

select x,y,z from table1 where id in (@p2) 
我没有收到返回的行吗?如果我修改相同的SQL以使用从上一个select中获得的相同字符串文字,我将获得行,好吗


如何将包含单引号标识符列表的字符串传递给SP并在子选择中使用?我在Google上搜索了很多,可以将列表转换为SP内的临时表并使用它,但我需要使用带引号的列表,以便使用OPTIMIZE FOR query提示。

中的
无法按您期望的方式处理逗号分隔的字符串:它被视为单个字符串,而不是隐式的值数组

('101102103')
中的
id将仅在
id
是精确的字符串
'101102103'
时匹配,而不是其任何单独的分隔块

您应该实现并返回一组其成员,并按如下方式使用它:

SELECT  *
FROM    table1
WHERE   id IN
        (
        SELECT  value
        FROM    tvf_split_string('101,102,103')
        )

一个选项是使用execute

Execute('select x,y,z from #1 where id in (' + @p2 + ')')

正如Quassnoi所说,您应该使用一个函数来拆分字符串。下面是我使用的一个:

CREATE FUNCTION dbo.tvf_split_string
(
    @List nvarchar(2000),
    @SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
    Id int identity(1,1),
    Value nvarchar(100)
) 
AS  
BEGIN 
    while (Charindex(@SplitOn,@List)>0)
    begin
        insert into @RtnValue (value)
        select 
            Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1)))

        set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
    end
    insert Into @RtnValue (Value)
    select Value = ltrim(rtrim(@List))

    return
END
并称之为:

从中选择值 dbo.tvf_分割_字符串('101102103')


伟大的正确的。我知道你是从哪里来的。我要试一下,然后回来。非常感谢。