Created
May 23, 2025 17:34
-
-
Save tcartwright/112965da6e56b9f5945083894fc82190 to your computer and use it in GitHub Desktop.
SQL SERVER: Create DTO from query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* JUST CHANGE THE CONTENTS OF THE @tsql variable to your query. It does not even need to produce rows */ | |
DECLARE @tsql NVARCHAR(MAX) = N' | |
SELECT TOP 10 [t].[name], | |
[t].[object_id], | |
[t].[schema_id], | |
[t].[type], | |
[t].[type_desc], | |
[t].[create_date] | |
FROM sys.[tables] AS [t] | |
WHERE OBJECTPROPERTY([t].[object_id], ''IsMSShipped'') = 0 | |
'; | |
-- Describe result set | |
SELECT | |
name, | |
system_type_name, | |
is_nullable | |
FROM sys.dm_exec_describe_first_result_set(@tsql, NULL, 0); | |
SELECT | |
'public ' + | |
CASE | |
WHEN system_type_name LIKE 'int%' THEN 'int' | |
WHEN system_type_name LIKE 'bigint%' THEN 'long' | |
WHEN system_type_name LIKE 'bit' THEN 'bool' | |
WHEN system_type_name LIKE 'varchar%' THEN 'string' | |
WHEN system_type_name LIKE 'nvarchar%' THEN 'string' | |
WHEN system_type_name LIKE 'char%' THEN 'string' | |
WHEN system_type_name LIKE 'datetime%' THEN 'DateTime' | |
WHEN system_type_name LIKE 'decimal%' THEN 'decimal' | |
WHEN system_type_name LIKE 'float%' THEN 'double' | |
ELSE 'object' | |
END + | |
CASE WHEN is_nullable = 1 AND system_type_name NOT LIKE '%char%' AND system_type_name NOT LIKE '%text%' THEN '?' ELSE '' END + ' ' + | |
name + ' { get; set; }' AS CSharpProperty | |
FROM sys.dm_exec_describe_first_result_set(@tsql, NULL, 0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment