我有一個需要修改的存儲過程。有4個可能的值可以通過變量@Company傳遞。該SQL看起來是這樣的....如何根據通過特定變量傳遞的值在我的存儲過程中編寫If語句?
-- Create #House table
CREATE TABLE #Houses
(
iHouse_ID int,
cName varchar(50),
cNumber varchar(10),
cPhoneNumber1 varchar(25),
cAddressLine1 varchar(50),
cCity varchar(30),
cStateCode varchar(2),
cZipCode varchar(10),
iUnitsAvailable int,
iRegOpsNumber int,
cOpsName varchar(50),
iRegionID int,
cRegionName varchar(50)
)
INSERT INTO #Houses (iHouse_ID, cName, cNumber, cPhoneNumber1, cAddressLine1, cCity, CStateCode, cZipCode, iUnitsAvailable, iRegOpsNumber, cOpsName, iRegionID, cRegionName)
SELECT
h2.iHouse_ID, h.cName, h.cNumber, h.cPhoneNumber1,
h.cAddressLine1, h.cCity, h.CStateCode, h.cZipCode,
h.iUnitsAvailable, r.RegOpsNumber, r.opsname,
r.iRegion_ID, r.regionname
FROM
rw.fn_GetScopeHouses (@Scope, @dtReport, NULL, NULL, 0) h2
JOIN
House h ON h.iHouse_ID = h2.iHouse_ID
AND h.cCompanyID = @CompanyID
JOIN
rw.vw_Reg_Ops r on r.opsareaID = h.iOpsArea_ID
現在,我必須作出修改是如果@CompanyID傳遞的變量是「0000」,那麼我需要在添加和h2.ihouse_ID沒有。是.so的SQL成爲...
FROM
rw.fn_GetScopeHouses (@Scope, @dtReport, NULL, NULL, 0) h2
JOIN
House h ON h.iHouse_ID = h2.iHouse_ID
AND h.cCompanyID = '0000'
JOIN
rw.vw_Reg_Ops r ON r.opsareaID = h.iOpsArea_ID
AND h2.ihouse_ID NOT IN (SELECT h2.iHouse_ID
FROM rw.fn_GetScopeHouses (0, getdate(), NULL, NULL, 0) h2
JOIN
House h ON h.iHouse_ID = h2.iHouse_ID
JOIN
rw.vw_Reg_Ops r ON r.opsareaID = h.iOpsArea_ID
JOIN
DBPROD02.houses_App.dbo.subAcct ON right(h.cGLSubaccount, 3) = RIGHT(RTRIM(consolsub), 3)
WHERE
S4future02 = 'FHLMC')
我想...
from rw.fn_GetScopeHouses (@Scope, @dtReport, NULL, NULL, 0) h2
JOIN House h on h.iHouse_ID = h2.iHouse_ID
AND h.cCompanyID = @CompanyID
JOIN rw.vw_Reg_Ops r on r.opsareaID = h.iOpsArea_ID
IF(@CompanyID = '0000')
BEGIN
AND h2.ihouse_ID not in (select h2.iHouse_ID
from rw.fn_GetScopeHouses (0, getdate(), NULL, NULL, 0) h2
JOIN House h on h.iHouse_ID = h2.iHouse_ID
JOIN rw.vw_Reg_Ops r on r.opsareaID = h.iOpsArea_ID
JOIN DBPROD02.houses_App.dbo.subAcct on right(h.cGLSubaccount,3)=RIGHT(RTRIM(consolsub), 3)
where S4future02 = 'FHLMC')
END
但是當我試圖保存更改,我得到了錯誤
Msg 137, Level 15, State 2, Line 186
Must declare the scalar variable "@CompanyID".
Msg 102, Level 15, State 1, Line 194
Incorrect syntax near 'END'.
變量已經在這裏宣佈...
ALTER PROCEDURE [rw].[sp_EFT_NoticeXLSNoDraw]
(@Scope varchar(50), @AcctPeriod char(6), @CompanyID nchar(10))
AS
我在如何繼續虧損。我究竟做錯了什麼?
您確定您可以將@CompanyID類型nchar(10)與任何類型的h.cCompanyID進行比較嗎? – FailedUnitTest
是的。傳遞的值是cCompanyID列中的值。 – Tetteh
首先,在放入查詢之前,您沒有聲明@CompanyID,使用'declare @companyID int',然後什麼是完整的SP代碼?第三,你需要在'if'子句中結合查詢條件,否則爲靜態條件,放在'where'後面,最後但並非最不重要的是,如果你不介意,查詢的語法有問題,粘貼整個SP – LONG