Skip to content

Instantly share code, notes, and snippets.

@jrichardsz
Last active May 2, 2025 15:26
Show Gist options
  • Save jrichardsz/98755cfc628e708f77e7d584e936f215 to your computer and use it in GitHub Desktop.
Save jrichardsz/98755cfc628e708f77e7d584e936f215 to your computer and use it in GitHub Desktop.
database advanced snippets

use quotes in table name

INNER JOIN acmeschema."FooTable"

solution

SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO

get column definition

SELECT 
  [Name]         = c.[name]
, [Type]         = 
    CASE 
      WHEN tp.[name] IN ('varchar', 'char', 'varbinary') THEN tp.[name] + '(' + IIF(c.max_length = -1, 'max', CAST(c.max_length AS VARCHAR(25))) + ')' 
      WHEN tp.[name] IN ('nvarchar','nchar') THEN tp.[name] + '(' + IIF(c.max_length = -1, 'max', CAST(c.max_length / 2 AS VARCHAR(25)))+ ')'      
      WHEN tp.[name] IN ('decimal', 'numeric') THEN tp.[name] + '(' + CAST(c.[precision] AS VARCHAR(25)) + ', ' + CAST(c.[scale] AS VARCHAR(25)) + ')'
      WHEN tp.[name] IN ('datetime2') THEN tp.[name] + '(' + CAST(c.[scale] AS VARCHAR(25)) + ')'
      ELSE tp.[name]
    END
, [RawType]      = tp.[name]
, [MaxLength]    = c.max_length
, [Precision]    = c.[precision]
, [Scale]        = c.scale
, [IsNullable]   = c.is_nullable
, [DefaultValue]   = object_definition(c.default_object_id)
FROM sys.tables t 
JOIN sys.schemas s ON t.schema_id = s.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
JOIN sys.types tp ON c.user_type_id = tp.user_type_id
WHERE s.[name] = 'dbo' AND t.[name] = 'Users';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment