sql - How can I make this query to accept dynamic table names? -
this function concats rows data 1 string. know function named coallasce available, out of curiosity want know how can change function accept table names dynamically. @ present reads employee table.
alter function [dbo].[concatstrig] ( @tablename varchar(64), @fieldname varchar(64) ) returns varchar(max) begin declare @sql varchar(max) = '' set @sql = 'select ' + @fieldname + ' ' + @tablename declare curtemp cursor select empname sp_executesql(@sql) declare @strtemp varchar(max) declare @string varchar(max) = '' open curtemp fetch next curtemp @strtemp while @@fetch_status = 0 begin set @string = @string + ' ' + @strtemp fetch next curtemp @strtemp end close curtemp deallocate curtemp return @string end
thanks in advance:)
you need use dynamic sql.
that's way parameterize table names.
Comments
Post a Comment