sql server - T-SQL : Script to create view with columns from a select statement -
i have bulk views create entire database.
to create view general syntax follows:
create view [table_name] select [column1], [column2], [column3], [column4] [table_name] check option;
i set column names in script above querying column names ([colulmn1]
, [column2]
, etc) information_schema.columns
.
is there way achieve table name?
coalesce friend programmer. want csv list of columns. using dynamic sql can auto generate rest of code.
declare @columns varchar(max) select @columns = null select @columns = coalesce(@columns+',','')+c.name syscolumns c inner join sysobjects o on c.id = o.id o.name = 'change me table name' select @columns select ' create view ' + 'cool view name' + ' ' + ' select ' + @columns + ' '+ ' change me table name '+ ' check option;'
edit
i purposely didn't declare view anywhere. if want declare view execute scripts so. but should never execute code on servers without reading all purposely excluded execution part think bad judgement cut , paste code , execute without understanding/testing.
declare @sql varchar(max) select @sql = ' create view ' + 'cool view name' + ' ' + ' select ' + @columns + ' '+ ' change me table name '+ ' check option;' exec(@sql);
Comments
Post a Comment