I took some code from a previous developer and came across this SQL statement that calls several SQL functions. As you can see, calling the function in the select statement passes the parameter to the function. How does an SQL statement know which value to replace with a variable? In the example below, how the query engine knows what to replace with nDeptID when it is called,fn_SelDeptName_DeptID(nDeptID)
nDeptIDIt is a column in a table Note.
SELECT STATEMENT:
SELECT nCustomerID AS [Customer ID],
nJobID AS [Job ID],
dbo.fn_SelDeptName_DeptID(nDeptID) AS Department,
nJobTaskID AS JobTaskID,
dbo.fn_SelDeptTaskDesc_OpenTask(nJobID, nJobTaskID) AS Task,
nStandardNoteID AS StandardNoteID,
dbo.fn_SelNoteTypeDesc(nNoteID) AS [Note Type],
dbo.fn_SelGPAStandardNote(nStandardNoteID) AS [Standard Note],
nEntryDate AS [Entry Date],
nUserName as [Added By],
nType AS Type,
nNote AS Note FROM Note
WHERE nJobID = 844261
ORDER BY nJobID, Task, [Entry Date]
========================
Function fn_SelDeptName_DeptID:
ALTER FUNCTION [dbo].[fn_SelDeptName_DeptID] (@iDeptID int)
RETURNS varchar(25)
BEGIN
DECLARE @strDeptName varchar(25)
IF @iDeptID = 0
SET @strDeptName = ''
ELSE
BEGIN
SET @strDeptName = (SELECT dName FROM Department WHERE dDeptID = @iDeptID)
IF (@strDeptName IS NULL) SET @strDeptName = ''
END
RETURN @strDeptName
END
============================
Thanks in advance.
source
share