Comma Delimited Result set + SQL Query

北战南征 提交于 2019-12-06 04:47:59

This is a very good approach and has become pretty well accepted. There are several approaches and this blog post describes a lot of them.

One interesting approach that exists is using the CLR to do the work for you which will significantly reduce the complexity of the query with the trade-off of running external code. Here is a sample of what the class might look like in the assembly.

using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;

[Serializable]
[SqlUserDefinedAggregate(Format.UserDefined,  MaxByteSize=8000)]
public struct strconcat : IBinarySerialize{

    private List values;

    public void Init()    {
        this.values = new List();
    }

    public void Accumulate(SqlString value)    {
        this.values.Add(value.Value);
    }

    public void Merge(strconcat value)    {
        this.values.AddRange(value.values.ToArray());
    }

    public SqlString Terminate()    {
        return new SqlString(string.Join(", ", this.values.ToArray()));
    }

    public void Read(BinaryReader r)    {
        int itemCount = r.ReadInt32();
        this.values = new List(itemCount);
        for (int i = 0; i <= itemCount - 1; i++)    {
            this.values.Add(r.ReadString());
        }
    }

    public void Write(BinaryWriter w)    {
        w.Write(this.values.Count);
        foreach (string s in this.values)      {
            w.Write(s);
        }
    }
}

And that would net a query a bit more like this.

SELECT CategoryId,
           dbo.strconcat(ProductName)
      FROM Products
     GROUP BY CategoryId ;

Which is quite a bit simpler obviously. Take it for what it's worth :)

Good day!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!