首页 / 数据库 / SQLServer / SQL Server2005数据项的分拆与合并
SQL Server2005数据项的分拆与合并2010-07-16 赛迪 VictorSQL 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