sqlserver2017版本包括以上的可以使用string_agg(字段,’,’)函数
sqlserver查询版本:
select @@version
Sql Server自定义聚合函数详细bai步骤
开始->
输出->
首先用baiVS2008/VS2005建立一个SQL Server项目,右键解决方案添加新项
点击“确定”bai按钮后,SQL Server项目会要求连接一个数据库,我们可以选择一个数据库
然后在工程中加入一个聚合类(joinstr.cs),如图
joinstr.cs中的最终代码如下:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text;[Serializable]
[SqlUserDefinedAggregate(Format.UserDefined, //use custom serialization to serialize the intermediate resultIsInvariantToNulls = true, //optimizer propertyIsInvariantToDuplicates = false, //optimizer propertyIsInvariantToOrder = false, //optimizer property MaxByteSize = 8000), //maximum size in bytes of persisted value
]public struct JoinStr:IBinarySerialize
{private StringBuilder sbIntermediate;public void Init(){sbIntermediate = new StringBuilder();}public void Accumulate(SqlString Value){if (Value == null || Value.ToString().ToLower().Equals("null")){return;}else{sbIntermediate.Append(Value);}}public void Merge(JionStr Group){sbIntermediate.Append(Group.sbIntermediate);}public SqlString Terminate(){return new SqlString(sbIntermediate.ToString());}// This is a place-holder member field#region IBinarySerialize Memberspublic void Read(System.IO.BinaryReader r){sbIntermediate = new StringBuilder(r.ReadString());}public void Write(System.IO.BinaryWriter w){w.Write(this.sbIntermediate.ToString()); }#endregion
}
在编写完上述代码后,可以使用Visual Studio来部署(右向工程,在弹出菜单上选“部署”即可)。
在执行上面的SQL语句之前,需要将SQL Server2005的clr功能打开
也可以用SQL打开clr功能:
EXEC sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE
GO
现在可以使用joinstr来聚合字符串了。
select [t_code_role].[role_mc] as '角色',dbo.JoinStr([t_code_right].[right_mc]+',') as '权限' from [t_data_roleright],[t_code_right],[t_code_role] where [t_data_roleright].[role_bm]=[t_code_role].[role_bm] and [t_data_roleright].[right_bm]=[t_code_right].[right_bm] group by [t_code_role].[role_mc]
转载地址:感谢 dyt0801
方案二:https://www.bbsmax.com/A/gVdnmXb15W/
方案三:http://blog.leanote.com/post/colin_xia@yeah.net/sql-server-%E6%B7%BB%E5%8A%A0%E5%AD%97%E7%AC%A6%E4%B8%B2%E8%81%9A%E5%90%88%E5%87%BD%E6%95%B0