Labels

Thursday, June 16, 2016

SQL Scripts Tips


@IS_INT = PATINDEX(‘%[^0-9]%’ ,@input)
@IS_ALPHA = PATINDEX(‘%[^A-Z]%’ ,@input)
@IsAlphaNumeric = PATINDEX('%[^a-Z,0-9,'' '']%', @input) > 0

@IsAlphaNumeric = NOT(@input LIKE '%[^a-Z,0-9,'' '']%')

How to get column names?
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Your Table Name'
ORDER BY ORDINAL_POSITION

How to create columns list from existing table?
select @col = stuff((select ','+quotename(C.COLUMN_NAME)
                     from INFORMATION_SCHEMA.COLUMNS as C
                     where C.TABLE_NAME = 'Table2'
                     order by C.ORDINAL_POSITION

                     for xml path(''), type).value('.',  'nvarchar(max)'), 1, 1, '');
set @sql = 'select '+@col+' into Table1 from Table2 union all '+

           'select '+@col+' from Table3';