select中的字符串文字在使用变量时返回不同的内容

时间:2017-04-21 16:59:57

标签: sql sql-server ssms

我有以下脚本,我在SSMS中使用Sql Server运行。我试图找到表格中的哪些列有"时间"列名称中的某个位置。

第一个选择显示正在访问的表中可用的列。

接下来的两个是我的问题。第一个将我的变量@timeColumn设置为字符串I' m寻找N'%time%'第二个使用文字本身。我希望这两个选择返回相同的列名,但他们不会。有什么想法吗?

USE MyLargeDB
declare @tableName NVARCHAR(100), @timeColumn NVARCHAR(100), @foundTimeCol NVARCHAR(100)
Set @tableName = N'Faults'
SET @timeColumn = N'%time%'
SELECT *
    FROM sys.columns 
    WHERE Name LIKE @timeColumn
      AND Object_ID = Object_ID(@tableName)

SET @foundTimeCol = (SELECT top 1 Name
    FROM sys.columns 
    WHERE Name LIKE @timeColumn
      AND Object_ID = Object_ID(@tableName))

print 'Found column with variable: ' + @foundTimeCol

SET @foundTimeCol = (SELECT top 1 Name
    FROM sys.columns 
    WHERE Name LIKE N'%time%'
      AND Object_ID = Object_ID(@tableName))
print 'Found column with literal string: ' + @foundTimeCol

输出:enter image description here enter image description here

1 个答案:

答案 0 :(得分:3)

您在SELECT中使用“TOP 1”,假设结果是有序的。在两个SELECT TOP 1语句中添加“ORDER BY Name”以获得相同的结果。当然这只会返回一个可能的匹配。

这样的事情:

SET @foundTimeCol = (SELECT top 1 Name
FROM sys.columns 
WHERE Name LIKE @timeColumn
  AND Object_ID = Object_ID(@tableName)
  ORDER BY Name)