相当简单的sql过程,当记录落在两个日期之间时,查看表中的字段是否等于true。目的是计算tue的实例,如果计数在输出参数中返回多个,则返回true。
CREATE PROCEDURE dbo.CheckIfLandingsForPeriodHaveBeenPosted @startDate DATE,
@endDate DATE,
@LandingsPosted BIT OUTPUT
AS
BEGIN
SET NOCOUNT ON
IF (SELECT
COUNT (
lh.Posted
FROM LandingHeaders lh
WHERE lh.LandingDate1 BETWEEN @startDate AND @endDate
AND lh.Posted = 1)
> 0
SET @LandingsPosted = 1
ELSE
SET @LandingsPosted = 0
END
GO
我尝试在lh.Posted = 1之后添加一个额外的括号并在ELSE之后立即删除SET语句但是没有帮助。
首先,我想知道为什么会在else语句中失败,但我也想知道是否有更优雅/有效的方法来创建这样的查询;在伪代码方面的内容如下:
检查这两个日期之间记录中的已过帐字段,如果发现任何一个为真,则返回true
答案 0 :(得分:2)
一种紧凑且高效的解决方案,完全避免使用IF ... ELSE
和COUNT
:
CREATE PROCEDURE dbo.CheckIfLandingsForPeriodHaveBeenPosted
@startDate DATE, @endDate DATE,
@LandingsPosted BIT = 0 OUTPUT --<- Set default to FALSE
AS
BEGIN
SELECT TOP 1 @LandingsPosted = 1 --<- Change to TRUE if at least one match is found
FROM LandingHeaders lh
WHERE lh.LandingDate1 BETWEEN @startDate AND @endDate
AND lh.Posted = 1
END
GO
答案 1 :(得分:1)
您忘了关注COUNT
并)
尝试关注:
CREATE PROCEDURE dbo.CheckIfLandingsForPeriodHaveBeenPosted @startDate DATE,
@endDate DATE,
@LandingsPosted BIT OUTPUT
AS
BEGIN
SET NOCOUNT ON
IF (SELECT
COUNT(lh.Posted)
FROM LandingHeaders lh
WHERE lh.LandingDate1 BETWEEN @startDate AND @endDate
AND lh.Posted = 1)
> 0
SET @LandingsPosted = 1
ELSE
SET @LandingsPosted = 0
END
GO
答案 2 :(得分:1)
这是一个简单的语法问题,因为您可以看到我所做的唯一更改是计数,您错过了一个&#39;)&#39;所以你查询无法编译。
该过程抛出一个错误,并不总是告诉你问题出在哪里,你可以随时认为问题就在它所说的位置。
CREATE PROCEDURE dbo.CheckIfLandingsForPeriodHaveBeenPosted @startDate DATE,
@endDate DATE,
@LandingsPosted BIT OUTPUT
AS
BEGIN
SET NOCOUNT ON
IF (SELECT
COUNT (lh.Posted)
FROM LandingHeaders lh
WHERE lh.LandingDate1 BETWEEN @startDate AND @endDate
AND lh.Posted = 1)
> 0
SET @LandingsPosted = 1
ELSE
SET @LandingsPosted = 0
END
GO