在like语句中使用SQL变量

时间:2014-05-01 15:08:04

标签: sql sql-server variables sql-like

我已经对此做了很多研究但是却无法做到这一点。我正在尝试使用以下内容查询审计跟踪:

declare @batchid char (30)
select @batchid='13857584'  --enter batch id here
declare @occurred int 
select @occurred='5'
print 'Batch is in system, check MRN and encounter. User also noted below'
select a.encounter, a.mrn, a.facility, c.fullname, t.action_desc, a.occurred, a.remark 
from audit..audit_trail a (nolock)
join cabinet..users c (nolock)
on a.userinstanceid=c.userinstanceid
join audit..action_table t (nolock)
on a.action=t.action
where a.REMARK like '%' +  @batchid  + '%'
and OCCURRED > GETDATE()-@occurred
order by a.occurred

由于某种原因它永远不会返回我想要的结果(没有结果)。但是当我专门为下面的批处理ID运行它时(而不是@batchid)

declare @batchid char (30)
select @batchid='13857584'  --enter batch id here
declare @occurred int 
select @occurred='5'
print 'Batch is in system, check MRN and encounter. User also noted below'
select a.encounter, a.mrn, a.facility, c.fullname, t.action_desc, a.occurred, a.remark 
from audit..audit_trail a (nolock)
join cabinet..users c (nolock)
on a.userinstanceid=c.userinstanceid
join audit..action_table t (nolock)
on a.action=t.action
where a.REMARK like '%' +  '13857584' + '%'
and OCCURRED > GETDATE()-@occurred
order by a.occurred

它完美无缺。我尝试在百分比符号之前和之后添加引号,但我不能正确。任何帮助赞赏。 SQL 2008

1 个答案:

答案 0 :(得分:5)

您关注将batchid声明为char

declare @batchid char (30)
select @batchid='13857584'  --enter batch id here

实际上,batchid被设置为:

'13857584______________________'

下划线用于显示空格字符,而不是实际的下划线。

尝试将其更改为varchar()

declare @batchid varchar(30);
select @batchid = '13857584';  --enter batch id here