SQL Server2005數據項的分拆與合並:
參考示例如下:
-- =============================================
-- Author: LzmTW
-- create date: 20080102
-- Description: 連接子字符串
-- @TableName: 數據所在的表的名稱
-- @KeyColName: 連接子字符串所依據的鍵值所在的列
-- @joinColName: 包含要連接的子字符串所在的列
-- @Quote: 分隔子字符串
-- @where: 選擇條件,不包含where
-- =============================================
create PROCEDURE [Helper].[joinValue]
@TableName nvarchar(100)
,@KeyColName nvarchar(20)
,@joinColName nvarchar(20)
,@Quote nvarchar(10) = N’,’
,@where nvarchar(max) = NULL
AS
BEGIN
SET NOcount ON;
DECLARE
@SQL nvarchar(max)
IF @where IS NULL
SET @SQL = N’
select *
FROM
(
select DISTINCT KeyCol = @KeyColName
FROM @TableName
)a
’
ELSE
SET @SQL = N’
select *
FROM
(
select DISTINCT KeyCol = @KeyColName
FROM @TableName
where @where
)a
’
SET @SQL = @SQL + N’
OUTER APPLY (
select NewValues =
STUFF(
REPLACE(
REPLACE(
REPLACE(
(
select joinCol = @joinColName
FROM @TableName b
where @KeyColName = a.KeyCol
FOR XML RAW
)
, N’’’’, N’’’’)
, N’’, N’’"/>’’, N’’’’)
, 1, LEN(N’’@Quote’’), N’’’’)
) c’
SET @SQL = REPLACE(@SQL, N’@TableName’, @TableName)
SET @SQL = REPLACE(@SQL, N’@KeyColName’, @KeyColName)
SET @SQL = REPLACE(@SQL, N’@joinColName’, @joinColName)
SET @SQL = REPLACE(@SQL, N’@Quote’, @Quote)
IF NOT @where IS NULL
SET @SQL = REPLACE(@SQL, N’@where’, @where)
--PRINT @SQL
exec sp_executesql @SQL
END
GO