I need to covert the following script to a function as follows:
1) change hard coded branchid and nameid to input parms
2) return "T" (char) if rows returned, "F" if no rows returned
******
---former borrower function
--********************************************************************************
declare
@branchid int,
@namesid int
set @branchid = 3208
set @namesid = 7619
(select
count(*)
from contracts c
inner join names n
on c.branchid = n.branchid
and c.namesid = n.namesid
inner join vwBcontrol v
on v.branchid = c.branchid
--where (loandate >= @startdate and loandate <= @enddate)
where (c.namesid = @namesid
and c.branchid = @branchid
and c.processstatus = 50 --former borrower
and c.loanamt > 0)
and not exists
(select contrnumber from contracts c2
where processstatus not in (3, 45, 47) --open, PandL, NonFile
and c2.namesid = c.namesid
and c2.branchid = c.branchid
and c2.payoutdate = c.loandate)
--and (c2.opendate < @enddate or (c2.opendate > c2.loandate and c2.loandate < @startdate)))
and not exists
(select contrid from transactions t
where transtype >= '3000' and transtype < '3999' and c.branchid = t.branchid and c.contrid = t.contrid
and t.namesid = c.namesid))
ASKER
I removed the two dates in your input parms. I had the related line of code to thos commented out. Do not need date params.
Here's error following by your solution that I edited out the unneeded params.
------------
Error:
Msg 170, Level 15, State 1, Procedure ABSFormerBorrower, Line 11
Line 11: Incorrect syntax near '('.
Msg 156, Level 15, State 1, Procedure ABSFormerBorrower, Line 32
Incorrect syntax near the keyword 'and'.
Msg 170, Level 15, State 1, Procedure ABSFormerBorrower, Line 35
Line 35: Incorrect syntax near ')'.
-------------------
Updated your function as follows:
-----
CREATE FUNCTION dbo.ABSFormerBorrower (
@branchid int,
@namesid int
)
RETURNS char(1)
AS
BEGIN
RETURN (
CASE WHEN EXISTS(
select top (1) 1
from dbo.contracts c
inner join dbo.names n
on c.branchid = n.branchid
and c.namesid = n.namesid
inner join dbo.vwBcontrol v
on v.branchid = c.branchid
where (c.namesid = @namesid
and c.branchid = @branchid
and c.processstatus = 50 --former borrower
and c.loanamt > 0)
and not exists
(select contrnumber from dbo.contracts c2
where processstatus not in (3, 45, 47) --open, PandL, NonFile
and c2.namesid = c.namesid
and c2.branchid = c.branchid
and c2.payoutdate = c.loandate)
and not exists
(select contrid from dbo.transactions t
where transtype >= '3000' and transtype < '3999' and c.branchid = t.branchid and c.contrid = t.contrid
and t.namesid = c.namesid))
THEN 'T' ELSE 'F' END
)
END --FUNCTION