Creazione di Custom TYPE: differenze tra le versioni

Da Webmobili Wiki.
Nessun oggetto della modifica
 
Riga 33: Riga 33:
<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
// Creare un DataTable per il TVP
// Creare un DataTable per il TVP
                DataTable tvpTable = new DataTable();
DataTable tvpTable = new DataTable();
                tvpTable.Columns.Add("Id", typeof(int));
tvpTable.Columns.Add("Id", typeof(int));
 
foreach (int id in ids)
                foreach (int id in ids)
{
                {
tvpTable.Rows.Add(id);
                    tvpTable.Rows.Add(id);
}
                }
</syntaxhighlight >
</syntaxhighlight >

Versione attuale delle 18:19, 18 feb 2025

Info

[modifica]

Se vogliamo passare a SQL Server un tipo complesso, ad esempio una lista bisogna usare le TVP (Table-Valued Parameter)

Per vedere tutti i TYPE presenti sul Database:

SELECT * FROM sys.types;

Creazione TYPE

[modifica]

Possiamo creare un tipo custom per una lista di interi come tabella:

CREATE TYPE IntList AS TABLE (Id INT);

Uso in SP

[modifica]
ALTER PROCEDURE [dbo].[UTILS_SPAM_remove_lead]
(
    @repositoryIds IntList READONLY  -- Usiamo il tipo creato sopra
)
AS
BEGIN
    SET NOCOUNT ON;
    -- Eliminare solo i record con repositoryID presenti nella lista
    DELETE FROM Lead WHERE repositoryID IN (SELECT Id FROM @repositoryIds);
END

Uso in C#

[modifica]
  • Creare un DataTable con gli ID
  • Passarlo come parametro alla stored procedure
// Creare un DataTable per il TVP
DataTable tvpTable = new DataTable();
tvpTable.Columns.Add("Id", typeof(int));
foreach (int id in ids)
{
 tvpTable.Rows.Add(id);
}