I've currently got a MSSQL stored procedure that uses multiple SQL functions to achieve a number of returns. Now I've been told about using sets rather than functions as it creates " bad code smell of a DBA who is not yet thinking in sets" Original Link
I'd like to better my code and love to know what sets are. So below are two of my functions from a long list of functions. Thanks to any that attempt the answer.
Function that returns a long list of values
CREATE FUNCTION dbo.funcGetPropertyEnviListFR
(
@PropertyId AS INT
)
RETURNS VARCHAR(200)
AS
BEGIN
DECLARE @ENVIFR VARCHAR(200)
SET @ENVIFR = ''
SELECT
@ENVIFR = COALESCE(@ENVIFR + ', ', '') + ENVIRONMENT.FR
FROM
ENVIRONMENT
INNER JOIN
MATRIXPROPENVIRONMENT
ON
MATRIXPROPENVIRONMENT.EnvironmentId = ENVIRONMENT.id
WHERE
MATRIXPROPENVIRONMENT.PropertyId = @PropertyId
ORDER BY
Weight
SET @ENVIFR = SUBSTRING(@ENVIFR, 3, 200)
RETURN @ENVIFR
END
Result may look like - Coastal, Village, Habitat
Function that returns a seller's ID
CREATE FUNCTION dbo.funcSellIdByPropId
(
@PropertyId AS INT
)
RETURNS INT
AS
BEGIN
DECLARE @ID AS INT
SET @ID = 0
SELECT
@ID = MATRIXAGENCYPROPERTY.AgencyId
FROM
MATRIXAGENCYPROPERTY
WHERE
MATRIXAGENCYPROPERTY.PropertyId = @PropertyId
IF @ID = 0
BEGIN
SELECT
@ID = PRIVATESELLERS.id
FROM
PRIVATESELLERS
WHERE
PRIVATESELLERS.PropertyId = @PropertyId
END
RETURN @ID
END
Result may look like - 43
Function that returns an image value from database
CREATE FUNCTION dbo.funcDefaultImage
(
@PropertyId INT,
@Position INT
)
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE @IMAGE VARCHAR(50)
SELECT @IMAGE = T.image
FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY weight DESC) AS [rownum],
PROPERTYGALLERY.image
FROM
PROPERTYGALLERY
WHERE
PROPERTYGALLERY.PropertyId = @PropertyId
) T
WHERE
rownum = @Position
RETURN @IMAGE
END
Result may look like - property_0001.png