-
Notifications
You must be signed in to change notification settings - Fork 1
/
SqlConnectionExtensions.cs
32 lines (28 loc) · 1.41 KB
/
SqlConnectionExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using AO.Models;
using Dapper;
using Microsoft.Data.SqlClient;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Excel2SqlServer.Library.Extensions
{
public static class SqlConnectionExtensions
{
public static bool TableExists(this SqlConnection connection, string schemaName, string tableName)
{
return (connection.QuerySingleOrDefault<int?>(
"SELECT 1 FROM [sys].[tables] WHERE [schema_id]=SCHEMA_ID(@schemaName) AND [name]=@tableName",
new { schemaName, tableName }) ?? 0) == 1;
}
public static bool SchemaExists(this SqlConnection connection, string schemaName)
{
return (connection.QuerySingleOrDefault<int?>(
"SELECT 1 FROM [sys].[schemas] WHERE [name]=@schemaName", new { schemaName }) ?? 0) == 1;
}
public static async Task<IEnumerable<string>> GetColumnNamesAsync(this SqlConnection connection, string schemaName, string tableName) =>
await GetColumnNamesAsync(connection, new ObjectName(schemaName, tableName));
public static async Task<IEnumerable<string>> GetColumnNamesAsync(this SqlConnection connection, ObjectName table) =>
await connection.QueryAsync<string>(
@"SELECT [col].[name] FROM [sys].[columns] [col] WHERE [object_id]=OBJECT_ID(@objectName)",
new { objectName = table.ToString() });
}
}