2016-02-03 141 views
0

相當簡單的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語句,但我也想知道是有創造擺在首位這種查詢更優雅/有效的方法;在僞代碼的東西線沿線的條款:

檢查張貼場在這兩個日期之間的記錄,如果發現是真的還真

+0

你缺少「)」關閉計數功能 –

+0

沒有你錯過了一個‘)’lh.Posted後?我認爲應該是從......中選擇count(lh.posted)...... –

+0

Doh我愚蠢我一直在最後加上括號 –

回答

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 
1

這是一個簡單的語法問題,因爲你可以看到我所做的就是在計數,你缺少一個「)」唯一的變化,所以你查詢不能編譯。

過程引發錯誤並不總是告訴你哪裏出了問題,你總是可以假定問題是它說它是。

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

緊湊,更高效的解決方案,避免兩者IF ... ELSECOUNT乾脆:

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