这是创建可重用列以逗号分隔的字符串的尝试。在这种情况下,我只有一个具有值的字符串,我不想要空字符串或空值。
首先,我创建一个用户定义类型,它是一个单列表。
-- ================================
-- Create User-defined Table Type
-- ================================
USE [RSINET.MVC]
GO
-- Create the data type
CREATE TYPE [dbo].[SingleVarcharColumn] AS TABLE
(
data NVARCHAR(max)
)
GO
该类型的真正目的是简化创建标量函数以将列放入逗号分隔值中。
-- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Rob Peterson
-- Create date: 8-26-2015
-- Description: This will take a single varchar column and convert it to
-- comma separated values.
-- =============================================
CREATE FUNCTION fnGetCommaSeparatedString
(
-- Add the parameters for the function here
@column AS [dbo].[SingleVarcharColumn] READONLY
)
RETURNS VARCHAR(max)
AS
BEGIN
-- Declare the return variable here
DECLARE @result VARCHAR(MAX)
DECLARE @current VARCHAR(MAX)
DECLARE @counter INT
DECLARE @c CURSOR
SET @result = ''
SET @counter = 0
-- Add the T-SQL statements to compute the return value here
SET @c = CURSOR FAST_FORWARD
FOR SELECT COALESCE(data,'') FROM @column
OPEN @c
FETCH NEXT FROM @c
INTO @current
WHILE @@FETCH_STATUS = 0
BEGIN
IF @result <> '' AND @current <> '' SET @result = @result + ',' + @current
IF @result = '' AND @current <> '' SET @result = @current
FETCH NEXT FROM @c
INTO @current
END
CLOSE @c
DEALLOCATE @c
-- Return the result of the function
RETURN @result
END
GO
现在,要使用这个。我将要转换为逗号分隔字符串的列选择为 SingleVarcharColumn 类型。
DECLARE @s as SingleVarcharColumn
INSERT INTO @s VALUES ('rob')
INSERT INTO @s VALUES ('paul')
INSERT INTO @s VALUES ('james')
INSERT INTO @s VALUES (null)
INSERT INTO @s
SELECT iClientID FROM [dbo].tClient
SELECT [dbo].fnGetCommaSeparatedString(@s)
得到这样的结果。
抢,保罗,詹姆斯,1,9,10,11,12,13,14,15,16,18,19,23,26,27,28,29,30,31,32,34,35,36, 37,38,39,40,41,42,44,45,46,47,48,49,50,52,53,54,56,57,59,60,61,62,63,64,65, 66,67,68,69,70,71,72,74,75,76,77,78,81,82,83,84,87,88,90,91,92,93,94,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,120,121,122,123,124,125,126,127,128,129,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159
我将我的 SingleVarcharColumn 类型中的数据列设置为 NVARCHAR(MAX),这可能会损害性能,但我正在寻找灵活性,并且它的运行速度足以满足我的目的。如果它是 varchar 并且宽度固定且较小,它可能会更快,但我还没有测试过。