How to get Column value without knowing column name ? SQL Server -
i have table name @table_name
i have column value @value don't have column name (but exist @ 1st position , can seek_id or prov_id ...i have compare value id )
how can compare table column name value ?
i want like
select * @table_name table.column[1].value = @value for example @table_name = bb_match , @value = 6
possible helpful -
query:
if object_id (n'dbo.bb_match') not null drop table dbo.bb_match create table dbo.bb_match (seek_id int, prov_id int) insert dbo.bb_match (seek_id, prov_id) values (6, 1), (2, 6) declare @columnid tinyint , @value int , @tablename sysname , @sql nvarchar(500) select @columnid = 1 , @value = 6 , @tablename = 'dbo.bb_match' select @sql = 'select * ' + @tablename + ' [' + c.name + '] = ' + cast(@value nvarchar(max)) sys.objects o (nowait) join sys.schemas s (nowait) on o.[schema_id] = s.[schema_id] join sys.columns c (nowait) on o.[object_id] = c.[object_id] o.[type] = 'u' -- <-- tables columns , s.name + '.' + o.name = @tablename , c.column_id = @columnid print @sql exec sp_executesql @sql shorter, unsafe (sys.columns contains column_name tables, views, procedures, ...):
select @sql = 'select * ' + @tablename + ' [' + c.name + '] = ' + cast(@value nvarchar(max)) sys.columns c (nowait) c.[object_id] = object_id(@tablename) , c.column_id = @columnid exec sys.sp_executesql @sql
output:
select * dbo.bb_match [seek_id] = 6 results:
seek_id prov_id ----------- ----------- 6 1
Comments
Post a Comment