加入收藏 | 设为首页 | 会员中心 | 我要投稿 济南站长网 (https://www.0531zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQL Server2005数据项的分拆与合并

发布时间:2016-09-11 13:11:13 所属栏目:MsSql教程 来源:站长网
导读:SQL Server2005数据项的分拆与合并: 参考示例如下: -- ============================================= -- Author: LzmTW -- create date: 20080102 -- Descri
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

(编辑:济南站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读