2013-02-08 35 views
0

任何人都可以解释这一点吗? 理论上两者都是相同的查询,但他们给出不同的答案。sql-server 2005中的动态与显式查询

一个)

declare @date varchar(10) 

set date = '03/02/2013' 

select count(*) from table1 where (from <= @date) and (@date <= to) 

B)

declare @date varchar(10) 

set date = '03/02/2013' 

set @sqlstring = 'select count(*) from table1 where (from <= ' + @date + ') and (' + @date + ' <= to)' 

exec sp_executeSql @sqlstring 

第一组句子给 '2',结果,这是正确的答案,但在第二组的句子,我有通过一个字符串动态执行相同的查询,但答案是'0'。

回答

0

在第一,有效的SQL是

select count(*) from table1 where (from <= '03/02/2013') and ('03/02/2013' <= to) 

在第二个,有效SQL是

select count(*) from table1 where (from <= 03/02/2013) and (03/02/2013 <= to) 

也就是说,第一个使用,不需要分隔符的变量。在第二个中,您有一个整数常量表达式,其中应用了“constant folding”。 3整数除以2时变为日期由2013 = 0 = 1900年1月1日分

你会需要这样的:

set @sqlstring = 'select count(*) from table1 
    where (from <= ''' + @date + ''') and (''' + @date + ''' <= to)' 

请注意,您应该使用yyyymmdd或ISO 8601日期一致性和清晰度

+0

非常感谢你GBN,这是绝对清楚的。 – user2053679