Using parameterized function calls in SELECT statements. SQL Server

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)

-- Used by DataCollection for Job Tracking
-- if the Deptartment isnt found return an empty string

BEGIN 
 -- Return the Department name for the given DeptID.
 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.

+3
source share
1 answer

, , SELECT nDeptID FROM Note. , , , .

, COALESCE . SQL, , --C-.

:

SELECT nCustomerID AS [Customer ID], 
 nJobID AS [Job ID], 
 COALESCE(d.Name, "") AS Department, 
 ...
 FROM Note 
 LEFT JOIN Departments d ON Note.nDeptID = d.nDeptID
 WHERE nJobID = 844261 
 xORDER BY nJobID, Task, [Entry Date]

, .

+7

Source: https://habr.com/ru/post/1741181/


All Articles