Skip to content

Instantly share code, notes, and snippets.

@yuriyostapenko
Created June 21, 2017 13:42
Show Gist options
  • Save yuriyostapenko/891d47892b1087c7e4ff964d47c5b0b9 to your computer and use it in GitHub Desktop.
Save yuriyostapenko/891d47892b1087c7e4ff964d47c5b0b9 to your computer and use it in GitHub Desktop.
Dapper TVP merge
--CREATE TABLE [dbo].[TheTable](
-- [Id] [bigint] NOT NULL,
-- [Text] [nvarchar](max) NULL,
-- CONSTRAINT [PK_TheTable] PRIMARY KEY CLUSTERED
--(
-- [Id] ASC
--)
--)
-- Type must exist for table-valued parameter
--CREATE TYPE [dbo].[TheTableType] AS TABLE(
-- [Id] [bigint] NOT NULL,
-- [Text] [nvarchar](max) NULL
--)
MERGE TheTable t
USING @data d
ON t.Id = d.Id
WHEN MATCHED THEN
UPDATE SET [Text] = d.[Text]
WHEN NOT MATCHED THEN
INSERT (Id, [Text]) VALUES (d.[Id], d.[Text]);
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using Dapper;
using Microsoft.SqlServer.Server;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
using (var conn = new SqlConnection("Data Source=.;Initial Catalog=disposable;Integrated Security=True"))
{
var dataset = GetFakeData();
conn.Execute(File.ReadAllText("merge.sql"), new {data = dataset.AsTableValuedParameter("dbo.TheTableType") });
}
}
private static List<SqlDataRecord> GetFakeData()
{
var metadata = new[]
{
new SqlMetaData("Id", SqlDbType.BigInt),
new SqlMetaData("Text", SqlDbType.Text)
};
var dataset = new[]
{
new {Id = 1, Text = "foo"},
new {Id = 2, Text = "bar"},
new {Id = 3, Text = "baz"},
new {Id = 4, Text = "bax"}
}.Select(i =>
{
var r = new SqlDataRecord(metadata);
r.SetInt64(0, i.Id);
r.SetString(1, i.Text);
return r;
}).ToList();
return dataset;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment