SQL 服务器中字符串的单引号

Single quotes for strings in SQL Server

DECLARE @rpmProvider varchar(200) = 'Prudhvi, raj,Lalith, Kumar';

DECLARE @xml xml
DECLARE @XMT_TEXT AS VARCHAR(200)

SET @XMT_TEXT = REPLACE(REPLACE(REPLACE(''''+ @rpmProvider + '''', ', ', '|'), ',', '</X><X>'), '|', ', ')
SET @xml = cast(('<X>' + @XMT_TEXT + '</X>') as xml)


SELECT N.value('.', 'varchar(50)') as value
FROM @xml.nodes('X') as T(N);

我的输出:

1. 'Prudhvi, raj
2. Lalith, Kumar'

预期输出:

1. 'Prudhvi, raj'
2. 'Lalith, Kumar'

像下面这样尝试

 DECLARE @rpmProvider varchar(200) = 'Prudhvi, raj,Lalith, Kumar';

DECLARE @xml xml
DECLARE @XMT_TEXT AS VARCHAR(200)

SET @XMT_TEXT = REPLACE(REPLACE(REPLACE(''''+ @rpmProvider + '''', ', ', '|'), ',', '</X><X>'), '|', ', ')
SET @xml = cast(('<X>' + @XMT_TEXT + '</X>') as xml)


SELECT case when left( N.value('.', 'varchar(50)'),1)=''''  then '' else
'''' end + N.value('.', 'varchar(50)')  +
case when right( N.value('.', 'varchar(50)'),1)=''''  then '' else
'''' end as value
FROM @xml.nodes('X') as T(N);



 value
'Prudhvi, raj'
'Lalith, Kumar'

demo link

您可以尝试以下查询,

DECLARE @rpmProvider varchar(200) = 'Prudhvi, raj,Lalith, Kumar';

DECLARE @xml xml
DECLARE @XMT_TEXT AS VARCHAR(200)

SET @XMT_TEXT = REPLACE(REPLACE(REPLACE(''''+ @rpmProvider + '''', ', ', '|'), ',', '''</X><X>'''), '|', ', ')
SET @xml = cast(('<X>' + @XMT_TEXT + '</X>') as xml)


SELECT N.value('.', 'varchar(50)') as value
FROM @xml.nodes('X') as T(N);

如果您删除与 XML 相关的所有代码并只留下

DECLARE @rpmProvider varchar(200) = 'Prudhvi, raj,Lalith, Kumar';
select REPLACE(REPLACE(REPLACE(''''+ @rpmProvider + '''', ', ', '|'), ',', '</X><X>'), '|', ', ') 

您会看到周围没有引号。结果是

'Prudhvi, raj</X><X>Lalith, Kumar'

您可以通过将替换字符串更改为 ''</X><X>'' 来解决此问题,并在标签前后添加两个单引号:

select REPLACE(REPLACE(REPLACE(''''+ @rpmProvider + '''', ', ', '|'), ',', '''</X><X>'''), '|', ', ')

现在的结果是:

'Prudhvi, raj'</X><X>'Lalith, Kumar'

尽管此代码非常 脆弱。它依赖于空格来分隔键、值和对。 SQL 这种语言在字符串解析和操作方面非常薄弱。这种解析应该在数据存储到数据库中之前完成。

试试这个

DECLARE @rpmProvider varchar(200) = 'Prudhvi, raj,Lalith, Kumar';

DECLARE @xml xml
DECLARE @XMT_TEXT AS VARCHAR(200)

SET @XMT_TEXT = REPLACE(REPLACE(REPLACE( @rpmProvider , ', ', '|'), ',', '</X><X>'), '|', ', ')

SET @xml = cast(('<X>' + @XMT_TEXT + '</X>') as xml)


SELECT ''''+N.value('.', 'varchar(50)')+'''' as value
FROM @xml.nodes('X') as T(N);