2017-07-17 54 views
1

我试图使用temp变量从表中检索数据。临时变量返回正确的数据,但当试图在查询中使用它时,它不会返回正确的数据集。 我试图在查询中使用硬编码的临时值检索数据,它工作正常。任何人都可以帮我找到这个问题。选择查询中使用的Temp变量

下面是我的代码,我已经试过

Declare @tempwordFinal varchar(50)          
select @tempwordFinal = ''''+'%'+'The Big Bang'+'%'+''''    
select @tempwordFinal --here the output is - '%The Big Bang%' 

SELECT * from MasterProgram where ProgramTitle like @tempwordFinal --not working 
SELECT * from MasterProgram where ProgramTitle like '%The Big Bang%' -- working 

回答

0

的问题是你(逃脱)额外的单引号。像这样''''。除非您在数据库中查找明确包含撇号的单词,否则不需要这些单词。更正后的代码看起来是这样的:

Declare @tempwordFinal As Varchar(50); 

Set @tempwordFinal = '%The Big Bang%'; 

Select @tempwordFinal; -- %The Big Bang% 

SELECT * from MasterProgram where ProgramTitle like @tempwordFinal; 
+0

请解释此代码的作用,请勿像这样删除代码。 – Boiethios

1

因为@tempwordFinal变量在开始和结束的单引号。所以它预计ProgramTitle列中的数据在开始和结束时都有单引号。除了通配符外,变量中的任何内容都将被视为数据,这就是它失败的原因。

select @tempwordFinal --here the output is - '%The Big Bang%' 
              ^   ^

当您使用变量varchar数据类型,我们并不需要使用单引号试试这个办法

Declare @tempwordFinal varchar(50)          
select @tempwordFinal = '%The Big Bang%' 

select 1 where 'The Big Bang' like @tempwordFinal 

。只有当您硬编码字符串常量时才需要单引号

相关问题