SQLServer(多语句表值函数代码)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

SQLServer(多语句表值函数代码)

代码如下:

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

go

CREATE FUNCTION

[dbo].[ufnGetContactInformation](@ContactID int)

RETURNS @retContactInformation TABLE

(

-- Columns returned by the function

[ContactID] int PRIMARY KEY NOT NULL,

[FirstName] [nvarchar](50) NULL,

[LastName] [nvarchar](50) NULL,

[JobTitle] [nvarchar](50) NULL,

[ContactType] [nvarchar](50) NULL

)

AS

-- Returns the first name, last name, job title and contact type for the specified contact.

BEGIN

DECLARE

@FirstName [nvarchar](50),

@LastName [nvarchar](50),

@JobTitle [nvarchar](50),

@ContactType [nvarchar](50);

-- Get common contact information

SELECT

@ContactID = ContactID,

@FirstName = FirstName,

@LastName = LastName

FROM [Person].[Contact]

WHERE [ContactID] = @ContactID;

SET @JobTitle =

CASE

-- Check for employee

WHEN EXISTS(SELECT * FROM [HumanResources].[Employee] e

WHERE e.[ContactID] = @ContactID)

THEN (SELECT [Title]

FROM [HumanResources].[Employee]

WHERE [ContactID] = @ContactID)

-- Check for vendor

WHEN EXISTS(SELECT * FROM

[Purchasing].[VendorContact] vc

INNER JOIN [Person].[ContactType] ct

ON vc.[ContactTypeID] = ct.[ContactTypeID]

WHERE vc.[ContactID] = @ContactID)

THEN (SELECT ct.[Name]

FROM [Purchasing].[VendorContact] vc

INNER JOIN [Person].[ContactType] ct

ON vc.[ContactTypeID] = ct.[ContactTypeID]

WHERE vc.[ContactID] = @ContactID)

-- Check for store

WHEN EXISTS(SELECT * FROM [Sales].[StoreContact] sc

INNER JOIN [Person].[ContactType] ct

ON sc.[ContactTypeID] = ct.[ContactTypeID]

WHERE sc.[ContactID] = @ContactID)

THEN (SELECT ct.[Name]

FROM [Sales].[StoreContact] sc

INNER JOIN [Person].[ContactType] ct

ON sc.[ContactTypeID] = ct.[ContactTypeID]

WHERE [ContactID] = @ContactID)

ELSE NULL

END;

SET @ContactType =

CASE

-- Check for employee

WHEN EXISTS(SELECT * FROM [HumanResources].[Employee] e

WHERE e.[ContactID] = @ContactID)

THEN 'Employee'

-- Check for vendor

WHEN EXISTS(SELECT * FROM

[Purchasing].[VendorContact] vc

INNER JOIN [Person].[ContactType] ct

ON vc.[ContactTypeID] = ct.[ContactTypeID]

WHERE vc.[ContactID] = @ContactID)

THEN 'Vendor Contact'

-- Check for store

WHEN EXISTS(SELECT * FROM [Sales].[StoreContact] sc

INNER JOIN [Person].[ContactType] ct

ON sc.[ContactTypeID] = ct.[ContactTypeID]

WHERE sc.[ContactID] = @ContactID)

THEN 'Store Contact'

-- Check for individual consumer

WHEN EXISTS(SELECT * FROM [Sales].[Individual] i

相关文档
最新文档