Tuesday, September 8, 2009

Timekeeper Name User Defined Function

This is similar in nature to the matter description udf described in the last post. The timekeeper name udf will return the last name, first name of the tkinit that is passed in the function.
USE [son_db]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[udfTKFullName]
(
@tkinit VARCHAR(5)
)
RETURNS VARCHAR(85)
AS
BEGIN

DECLARE @fullname VARCHAR(85)

SELECT @fullname = tklast + (CASE WHEN tkfirst IS NULL THEN '' ELSE ', ' END) + ISNULL(tkfirst,'')
FROM timekeep
WHERE tkinit = @tkinit

RETURN @fullname

END
To use the user defined function, simply invoke it in the SELECT statement and pass it a value to execute on.
SELECT dbo.udfTKFullName(tkinit)
FROM timekeep
WHERE tkinit = '1234'
Using a UDF here will help you avoid having to CONCATENATE or COALESCE the parts of the name in each query.

No comments:

Post a Comment