两个查询返回不同的数据

时间:2016-05-13 10:05:22

标签: sql sql-server sql-server-2012

下面我有两个问题,对我来说是相同的,所以应该返回相同的结果。但他们没有,底层查询没有返回任何数据,但我不明白为什么?

查询下面返回正确的数据

SELECT        myDate, myTicker, SUM(myUnits) AS mUnits
FROM          myTbl
where myName = 'abc4' and myDate >= '2016-04-13'
GROUP BY myDate, myTicker

下面的查询返回零行,虽然我不明白为什么它对我来说与上面的查询相同。

declare @myF nvarchar, @FromDate date
set @myF = 'abc4'
set @FromDate = '2016-04-13'
SELECT        myDate, myTicker, SUM(myUnits) AS mUnits
FROM          myTbl
where myName = @myF and myDate >= @FromDate
GROUP BY myDate, myTicker

更新

下面的查询有效,似乎麻烦查询不喜欢@myF变量

declare @myF nvarchar, @FromDate date
set @myF = 'abc4'
set @FromDate = '2016-04-13'
SELECT        myDate, myTicker, SUM(myUnits) AS mUnits
FROM          myTbl
where myName = 'abc4' and myDate >= @FromDate
GROUP BY myDate, myTicker

3 个答案:

答案 0 :(得分:3)

设置NVARCHAR(4)

的大小
DECLARE @myF NVARCHAR(4), @FromDate DATE
SET @myF = 'abc4'

答案 1 :(得分:1)

以下两个查询对我有效,并且相同。

查询#1:

SELECT  myDate, myTicker, SUM(myUnits) AS mUnits
FROM    myTbl
WHERE   myName = 'abc4' and myDate >= '2016-04-13'
GROUP   BY myDate, myTicker


查询#2:

DECLARE @myF NVARCHAR(MAX), @FromDate DATE
SET     @myF        = 'abc4'
SET     @FromDate   = '2016-04-13'

SELECT  myDate, myTicker, SUM(myUnits) AS mUnits
FROM    myTbl
where   myName = @myF AND myDate >= @FromDate
GROUP   BY myDate, myTicker

答案 2 :(得分:1)

主要原因是Default Length的{​​{1}}为NVARCHAR

所以,你的这个查询

1

返回查询与第一个查询比较,

declare @myF nvarchar, @FromDate date
set @myF = 'abc4'
set @FromDate = '2016-04-13'
SELECT        myDate, myTicker, SUM(myUnits) AS mUnits
FROM          myTbl
where myName = @myF and myDate >= @FromDate
GROUP BY myDate, myTicker

这就是为什么你们两个查询不相等的原因。

您需要指定SELECT myDate, myTicker, SUM(myUnits) AS mUnits FROM myTbl where myName = 'a' and myDate >= '2016-04-13' GROUP BY myDate, myTicker 变量的Length,例如..

NVARCHAR

然后你就会得到预期的结果。