我附上一個CTE的代碼,它可以正常工作。我試圖從一個函數內運行它,我從來沒有做過,並得到我簡單可以修復的錯誤。更多的關注這個問題將不勝感激。我不覺得有必要解釋CTE代碼,因爲它可以很好地工作,問題在於它被描述爲一個函數。下面是代碼和SQL Server 2008 R2的錯誤消息:未解決的錯誤代碼
USE Med
Go
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Robert G. Seminario
-- Create date: 5/19/2017
-- Description: Joint Credit Not Checked
-- =============================================
CREATE FUNCTION [dbo].[fn_JointCreNotCk]
(@din as Nvarchar (40), @jin as Nvarchar(30)) -- Pass in Donor_ID_Number and Joint_ID_Number
RETURNS Nvarchar(40)
AS
BEGIN
Return
(
Go
With dn_cte (TRANSACTION_ID, Donor_ID_Number, ID_Number, DonorFound)
AS
(
Select
olg.TRANSACTION_ID, olg.Donor_ID_Number, lmc.Id_Number,
(CASE When lmc.Id_Number = @din THEN '1' ELSE '0' END) as DonorFound
from OnlineGivingDailyLoad as olg
left outer join LMC_ENTITY as lmc
on lmc.Id_Number = olg.Donor_ID_Number
),
Jt_cte as
(
Select
olg.TRANSACTION_ID, olg.Joint_ID_Number, lmc.Id_Number,
CASE When lmc.Id_Number = @jin THEN '1' ELSE '0' END As JointFound
from OnlineGivingDailyLoad as olg
left outer join LMC_ENTITY as lmc
on lmc.Id_Number = olg.Joint_ID_Number
),
dnjnt_cte as
(
Select
olg.TRANSACTION_ID, olg.Donor_ID_Number,
(CASE WHEN e.jnt_Gifts_ind = 'Y' THEN '1' ELSE '0' END)as D_JntGI
from OnlineGivingDailyLoad as olg
left outer join Advance.dbo.ENTITY as e
on e.ID_NUMBER = olg.Donor_ID_Number
),
Jtjnt_cte as
(
Select
olg.TRANSACTION_ID, olg.Joint_ID_Number,
(CASE WHEN e.jnt_Gifts_ind = 'Y' THEN '1' ELSE '0' END)as J_JntGI
from OnlineGivingDailyLoad as olg
left outer join Advance.dbo.ENTITY as e
on e.ID_NUMBER = olg.Joint_ID_Number
),
JtCkNotCk as
(
Select dn_cte.TRANSACTION_ID,
(Case WHEN cast(dn_cte.DonorFound as int) + cast(Jt_cte.JointFound as int) = 2 THEN 1 ELSE 0 END)as BothFound,
(CASE WHEN cast(dnjnt_cte.D_JntGI as int) + cast(Jtjnt_cte.J_JntGI as int) = 2 THEN 1 ELSE 0 END)as JointG
from dn_cte
inner join jt_cte
on Jt_cte.TRANSACTION_ID = dn_cte.TRANSACTION_ID
inner join dnjnt_cte
on dnjnt_cte.TRANSACTION_ID = dn_cte.TRANSACTION_ID
inner join Jtjnt_cte
on Jtjnt_cte.TRANSACTION_ID = dn_cte.TRANSACTION_ID
)
Select TRANSACTION_ID, (CASE WHEN (BothFound + JointG) = 2 THEN 1 ELSE 0 END) AS Final
from JtCkNotCk
order by 1
)
END
Go
現在的錯誤信息:
消息102,級別15,狀態1,過程fn_JointCreNotCk,行16
附近有語法錯誤'('。
消息137,級別15,狀態2,行8
必須聲明標量變量 「@din」。
消息137,級別15,狀態2,行19
必須聲明第e標量變量「@jin」。
Msg 102,Level 15,State 1,Line 37
','附近的語法不正確。
Msg 102,Level 15,State 1,Line 48
','附近語法不正確。
Msg 102,Level 15,State 1,Line 68
')'附近的語法不正確。
幫助表示讚賞。
側面說明,請不要使用1'爲了' - 指定實際列名 – Adam