SQL Server2005数据项的分拆与合并
2010-07-16 15:44:19 来源:WEB开发网-- =============================================
-- Author: LzmTW
-- create date: 20080102
-- Description: 分拆字符串
-- @TableName: 数据所在的表的名称
-- @KeyColName: 分拆为子字符串所依据的键值所在的列
-- @SpliteColName: 包含要分拆的字符串所在的列
-- @Quote: 分隔子字符串
-- @where: 选择条件,不包含where
-- =============================================
create PROCEDURE [Helper].[SpliteValues]
@TableName nvarchar(100)
,@KeyColName nvarchar(20)
,@SpliteColName 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
KeyCol, NewValue
FROM
(
select
KeyCol = @KeyColName
,SpliteCol = CONVERT(xml, N’’’’ + REPLACE(@SpliteColName, N’’@Quote’’, N’’’’) + N’’’’)
FROM @TableName
) a
’
ELSE
SET @SQL = N’
select
KeyCol, NewValue
FROM
(
select
KeyCol = @KeyColName
,SpliteCol = CONVERT(xml, N’’’’ + REPLACE(@SpliteColName, N’’@Quote’’, N’’’’) + N’’’’)
FROM @TableName
where @where
) a
’
SET @SQL = @SQL + N’
OUTER APPLY
(
select NewValue = N.v.value(N’’.’’, ’’nvarchar(max)’’)
FROM SpliteCol.nodes(N’’/root/v’’) N(v)
) b’
SET @SQL = REPLACE(@SQL, N’@TableName’, @TableName)
SET @SQL = REPLACE(@SQL, N’@KeyColName’, @KeyColName)
SET @SQL = REPLACE(@SQL, N’@SpliteColName’, @SpliteColName)
SET @SQL = REPLACE(@SQL, N’@Quote’, @Quote)
IF NOT @where IS NULL
SET @SQL = REPLACE(@SQL, N’@where’, @where)
exec sp_executesql @Sql
END
更多精彩
赞助商链接