Dynamic Query to list all column Alphabetically.
DECLARE @QUERY VARCHAR(4000)SET @QUERY = 'SELECT '
SELECT @QUERY = @QUERY + Column_name + ',' + CHAR(13) + CHAR(10) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'<TableName>' ORDER BY Column_name
SET @QUERY = @QUERY + 'FROM <TableName> '
PRINT @QUERY
Note:- Replace <TableName> with your table name .Also if you want all fields in a string ( a,b,c,d etc) then remove CHAR(13) + CHAR(10)
Update :-
Underscore (_) and quotes within SQL LIKE queries
Suppose we have a field having data 'xxxx_S' now We have to select Table Columns having '_S'
DECLARE @QUERY VARCHAR(4000)
SET @QUERY = 'SELECT '
SELECT @QUERY = @QUERY + Column_name + ','
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'insuredinfo' AND Column_name LIKE '%' + char(13) + '_S' escape char(13)
SET @QUERY = @QUERY + 'FROM insuredinfo'
PRINT @QUERY
No comments:
Post a Comment