sql - Save fieldname and fieldvalues -
i want save values, field names of table in table.
target table:targettable
source table:mysourcetable
i want run follows:
exec fieldvevaluewrite("mysourcetable") create table [dbo].[targettable]( [fieldname] [nchar](50) null, [fieldvalue] [nchar](300) null ) on [primary]
output follows:
[fieldname] [fieldvalue] name vedat surname pala city tokat counrty tÜrkİye
same answer same question:
declare @tablename varchar(50) = 'mysourcetable'; declare @columns varchar(4000) = ''; declare @insertvalues varchar(4000) = ''; declare @columnsvar varchar(4000) = ''; declare @sql varchar(max); select @columns = @columns + '[' + column_name + ']' information_schema.columns table_name = @tablename select @insertvalues = @insertvalues + '(''' + column_name + ''',@' + column_name + '),' information_schema.columns table_name = @tablename set @columnsvar = replace(replace(@columns,'[','@'),']',','); set @columnsvar = left(@columnsvar, len(@columnsvar)-1); set @insertvalues = left(@insertvalues, len(@insertvalues)-1); set @sql = @columns; set @sql = replace(@sql,'[','declare @'); set @sql = replace(@sql,']',' nvarchar(300);'); set @sql = @sql + 'declare rowcursor cursor '; set @sql = @sql + 'select * ' + @tablename + ';'; set @sql = @sql + 'open rowcursor '; set @sql = @sql + 'fetch next rowcursor ' + @columnsvar + '; '; set @sql = @sql + 'while @@fetch_status = 0 ' ; set @sql = @sql + 'begin '; set @sql = @sql + 'insert targettable values ' + @insertvalues + ';'; set @sql = @sql + 'fetch next rowcursor ' + @columnsvar + '; '; set @sql = @sql + 'end '; set @sql = @sql + 'close rowcursor '; set @sql = @sql + 'deallocate rowcursor '; exec(@sql)
Comments
Post a Comment