我有以下脚本,我在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
答案 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)