Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Set di risultati delimitati da virgole + query SQL

Questo è un ottimo approccio ed è diventato abbastanza ben accettato. Esistono diversi approcci e questo post del blog descrive molto di loro.

Un approccio interessante che esiste è usare CLR per fare il lavoro per te che ridurrà significativamente la complessità della query con il compromesso dell'esecuzione di codice esterno. Ecco un esempio di come potrebbe apparire la classe nell'assemblea.

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);
        }
    }
}

E ciò renderebbe una query un po' più simile a questa.

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

Il che è un po' più semplice ovviamente. Prendilo per quello che vale :)

Buona giornata!