我写这个是为了从表中的任何列搜索sql中的字符串,但在某些情况下它会异常响应。这里给出了一个例子。
declare @tablepay table
(
payno varchar(500),
lastmodified nvarchar(500)
)
declare @columnname table
(
[rownumber] INT IDENTITY,
colname varchar(500)
)
insert into @tablepay (payno, lastmodified)
select 'PAY/2014','abcd'
insert into @columnname(colname)
select TN.N.value('local-name(.)', 'sysname') as ColumnName
from
(select TV.*
from (select 1) as D(N)
outer apply (select top(0) * from @tablepay) as TV for xml path(''), elements xsinil, type) as TX(X)
cross apply TX.X.nodes('*') as TN(N)
DECLARE @count INT
DECLARE @begincount INT
DECLARE @clname as VARCHAR(50)='';
SET @begincount = 1
select @count = count(*) from @columnname
declare @tlname varchar(50)
set @tlname = '@tablepay'
WHILE @begincount <= @count
BEGIN
set @clname = (select colname from @columnname where rownumber = @begincount)
declare @text as varchar(100)
select * from @tablepay where @clname like '%f%'
SET @begincount = @begincount + 1
END
答案 0 :(得分:1)
你说when I give like '%f%' it returns a row. But in that row there is no 'f'
那应该是正确的。在您的以下查询@clname
不是表变量@tablepay
的一部分。所以它只是检查@clname
参数值是否包含f
个字符,以及true
是否从表@tablepay
返回行但是并不保证该表@tablepay
1}}必须有一行在其列中包含f
个字符。
select * from @tablepay where @clname like '%f%'
您的每个结构表@tablepay
如下
declare @tablepay table
(
payno varchar(500),
lastmodified nvarchar(500)
)
如果要在该表的列中搜索字符f
,请直接搜索表格列,如
select * from @tablepay where payno like '%f%' OR lastmodified like '%f%'
答案 1 :(得分:0)
请参阅此现有答案,了解您认为您要求的内容的示例:
Selecting column names that have specified value
此特定答案搜索数据库中所有表中的所有字符串列。您可以轻松修改它以仅搜索一个特定表中的所有字符串列。它应该为您提供调整以获得所需内容所需的框架。