如何在不知道列名的情况下获取Column值? SQL Server

时间:2013-05-10 10:05:13

标签: sql sql-server stored-procedures sysobjects

我的表名为@Table_Name

我的列值为@Value,但没有列名(但是它存在于第一个位置,可以是Seek_id或prov_id ......我必须将我的值与此id进行比较)

如何比较该表列名称值?

我想要像

这样的东西
SELECT * FROM @Table_Name
WHERE Table.Column[1].Value = @Value

例如@Table_Name = bb_match@Value = 6

2 个答案:

答案 0 :(得分:2)

这可能对你有所帮助 -

<强>查询:

IF OBJECT_ID (N'dbo.bb_match') IS NOT NULL
   DROP TABLE dbo.bb_match

CREATE TABLE dbo.bb_match (seek_id INT, prov_id INT)

INSERT INTO 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 * FROM ' + @TableName + ' WHERE [' + c.name + '] = ' + CAST(@Value AS NVARCHAR(MAX))
FROM sys.objects o WITH (NOWAIT)
JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
JOIN sys.columns c WITH (NOWAIT) ON o.[object_id] = c.[object_id]
WHERE o.[type] = 'U' -- <-- only for tables columns
    AND s.name + '.' + o.name = @TableName
    AND c.column_id = @ColumnID

PRINT @SQL

EXEC sp_executesql @SQL

更短但不安全(sys.columns包含表格,视图,过程的column_name ......):

SELECT @SQL = 'SELECT * FROM ' + @TableName + ' WHERE [' + c.name + '] = ' + CAST(@Value AS NVARCHAR(MAX))
FROM sys.columns c WITH (NOWAIT)
WHERE c.[object_id] = OBJECT_ID(@TableName)
    AND c.column_id = @ColumnID

EXEC sys.sp_executesql @SQL

<强>输出:

SELECT * FROM dbo.bb_match WHERE [seek_id] = 6

<强>结果:

seek_id     prov_id
----------- -----------
6           1

答案 1 :(得分:0)

declare @sql varchar(MAX)
declare @tablename varchar(100) = 'MyTable' --add your table name here
declare @value varchar(100) = 'SomeValue' -- add your desired value hree

select @sql = 'SELECT * FROM ' + @tablename + ' WHERE '
+ name 
+ ' = ''' + @value + ''''
from sys.columns where object_id = object_id(@tablename) and column_id = 1

exec (@sql)

这有三个部分。首先,我宣布三个字符串。 @sql是我构建查询的地方,@tablename@value是要查看/ for的表和搜索值。我已经输入了虚拟值MyTable和SomeValue来显示我正在谈论的内容

接下来我构建了sql语句。第一行将字符串设置为SELECT * FROM MyTable WHERE

然后我通过从SQL SERver系统表sys.columns中选择Name来添加列名,在第一列(column_id = 1)和表名

上进行过滤

下一步是在列中添加我们想要搜索的值。

最后,EXEC(@sql)将字符串解释为命令并运行它。