1

我有表名@Table_Name

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

如何比较该表列名称值?

我想要类似的东西

SELECT * FROM @Table_Name
WHERE Table.Column[1].Value = @Value

例如@Table_Name = bb_match@Value = 6

4

2 回答 2

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

执行 sys.sp_executesql @SQL

输出:

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

结果:

seek_id     prov_id
----------- -----------
6           1
于 2013-05-10T10:08:57.430 回答
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要查找/查找的表和搜索值。我已经输入了虚拟值 MyTable 和 SomeValue 来显示我在说什么

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

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

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

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

于 2013-05-10T10:22:47.440 回答