-- 将多行记录(只能一个列)用指定分隔符分隔 IF(OBJECT_ID(‘sp_RowsChangeClosBySplit‘,N‘P‘) IS NOT NULL) DROP PROC sp_RowsChangeClosBySplit GO CREATE PROC sp_RowsChangeClosBySplit @table nvarchar(50), -- 表名 @field nvarchar(50), -- 要拼接的字段 @split varchar(10)=‘,‘, -- 分隔符 @where nvarchar(500)=‘‘ -- 条件 AS BEGIN DECLARE @sql NVARCHAR(1000) SET @sql=‘select TOP 1 stuff((select ‘‘‘+@split+‘‘‘+convert(varchar(50),‘+@field+‘) from ‘+@table+‘ ‘+@where+‘ FOR XML PATH(‘‘‘‘)), 1, 1, ‘‘‘‘) as cols from ‘+@table+‘ group by ‘+@field PRINT @sql EXEC sp_executesql @sql END
调用:
EXEC dbo.sp_RowsChangeClosBySplit @table = N‘pro_Household‘, -- nvarchar(50) @field = N‘ID‘, -- nvarchar(50) @split = ‘,‘, -- varchar(10) @where = N‘where id < 10‘ -- nvarchar(500)
分割后:结果集:
普通查询:
SELECT ID FROM dbo.pro_Household WHERE ID<10
分割钱:结果集
时间: 2024-10-09 03:32:48