TSQL:不能在while循环中连接字符串

时间:2017-11-30 04:56:28

标签: sql-server tsql sql-server-2012

尝试使用代码

连接字符串
DECLARE @separator [nchar](1) = '|',
         @urlList [nvarchar](4000) = '',
         @urlTemp [nvarchar](4000);

DECLARE UrlCursor CURSOR FOR
SELECT [FileName] FROM [stgInfo];

OPEN UrlCursor;
FETCH NEXT FROM UrlCursor INTO @urlTemp;
SET @urlList += @urlTemp;

WHILE @@FETCH_STATUS = 0
   BEGIN
         SET @urlList += @separator + @urlTemp;
         FETCH NEXT FROM UrlCursor INTO @urlTemp;
   END
CLOSE UrlCursor;
DEALLOCATE UrlCursor;

所以,在@urlList我只得到一个值。

但打印

   BEGIN
         print @urlTemp;
         FETCH NEXT FROM UrlCursor INTO @urlTemp;
   END

也会返回所有值。

有人可以解释如何修复脚本以获取所有值吗?

此处的表格声明:

SET QUOTED_IDENTIFIER ON;
GO

CREATE TABLE [stgInfo]
(
    [Guid]      [uniqueidentifier] NOT NULL,
    [Number]    [nvarchar](100)    NULL,
    [OrderDate] [nvarchar](20)     NULL,
    [JrnType]   [nchar](10)        NULL,
    [Status]    [nchar](20)        NULL,
    [FileName]  [nchar](300)       NULL,

    CONSTRAINT   [PK_stgInfo] PRIMARY KEY CLUSTERED 
    (
         [Guid] ASC
    )
    WITH
    (
         PAD_INDEX = OFF,
         STATISTICS_NORECOMPUTE = OFF,
         IGNORE_DUP_KEY = OFF,
         ALLOW_ROW_LOCKS = ON,
         ALLOW_PAGE_LOCKS = ON
    )
    ON [PRIMARY]
)
ON [PRIMARY];
GO

遵循stackoverflow的规则我将此文本添加到我的问题中,因为它说问题主要包含代码。

3 个答案:

答案 0 :(得分:4)

以下是使用以下示例数据的四种不同方法:

-- using table variable for sample data
declare @stginfo table ([filename] varchar(4000));
insert @stginfo values ('abc.txt'),('zzz.sql'),('hellokitty.bat');

选项1:变量连接

DECLARE @separator [nchar](1) = N'|',
         @urlList [nvarchar](4000) = N'',
         @urlTemp [nvarchar](4000);

SELECT @urlList += [FileName]+@separator
FROM @stgInfo; -- Order by is not guaranteed with this method

SELECT urlList = substring(@urlList,1,len(@urlList)-1);

选项2:用于xml路径('')无XML保护

SELECT urlList = 
STUFF((
  SELECT [filename] + @separator
  FROM @stginfo
  ORDER BY [filename] -- only required if you must get this text in a specific order
  FOR XML PATH('')),1,1,'')

选项3:用于xml路径('')使用XML保护

SELECT urlList = 
STUFF((
  SELECT [filename] + @separator
  FROM @stginfo
  FOR XML PATH(''), TYPE).value('(text())[1]', 'nvarchar(4000)'),1,1,'')

选项4:STRING_AGG(仅限SQL Server 2017)

SELECT urlList = STRING_AGG([filename],'|') WITHIN GROUP (ORDER BY [Filename])
FROM @stginfo;

答案 1 :(得分:3)

模仿群组连结的推荐方法是使用for xmlstuff

SELECT @urlList = STUFF(
    (SELECT '|' + [FileName] 
     FROM [stgInfo]
     FOR XML PATH(''))
, 1, 1, '')

内部选择将分隔符与列值连接,并且东西删除第一个分隔符。

答案 2 :(得分:1)

问题出在数据格式[FileName][nchar](300) NULL, - 只需要更改为nvarchar。感谢大家提供出色的解决方案,我当然会使用它们。