2011-09-21 41 views
-2

我有要求從案例語句中的表中選擇字段,而不是一些靜態值。當存在的話,然後選擇

WHEN EXISTS(SELECT c.customer_name FROM Sales.Customer AS c 
      WHERE c.PersonID = @BusinessEntityID) 

      THEN c.customer_name 

這是如何實現的或者這是可能的。我從msdn網站採取了以下內容。需要調整以滿足我的要求。

USE AdventureWorks2008R2; 
GO 
CREATE FUNCTION dbo.GetContactInformation(@BusinessEntityID int) 
RETURNS @retContactInformation TABLE 
(
BusinessEntityID int NOT NULL, 
FirstName nvarchar(50) NULL, 
LastName nvarchar(50) NULL, 
ContactType nvarchar(50) NULL, 
PRIMARY KEY CLUSTERED (BusinessEntityID ASC) 
) 
AS 
-- Returns the first name, last name and contact type for the specified contact. 
BEGIN 
DECLARE 
    @FirstName nvarchar(50), 
    @LastName nvarchar(50), 
    @ContactType nvarchar(50); 

-- Get common contact information 
SELECT 
    @BusinessEntityID = BusinessEntityID, 
    @FirstName = FirstName, 
    @LastName = LastName 
FROM Person.Person 
WHERE BusinessEntityID = @BusinessEntityID; 

SET @ContactType = 
    CASE 
     -- Check for employee 
     WHEN EXISTS(SELECT * FROM HumanResources.Employee AS e 
      WHERE e.BusinessEntityID = @BusinessEntityID) 
      THEN 'Employee' 

     -- Check for vendor 
     WHEN EXISTS(SELECT * FROM Person.BusinessEntityContact AS bec 
      WHERE bec.BusinessEntityID = @BusinessEntityID) 
      THEN 'Vendor' 

     -- Check for store 
     WHEN EXISTS(SELECT * FROM Purchasing.Vendor AS v   
      WHERE v.BusinessEntityID = @BusinessEntityID) 
      THEN 'Store Contact' 

     -- Check for individual consumer 
     WHEN EXISTS(SELECT * FROM Sales.Customer AS c 
      WHERE c.PersonID = @BusinessEntityID) 
      THEN 'Consumer' 
    END; 

-- Return the information to the caller 
IF @BusinessEntityID IS NOT NULL 
BEGIN 
    INSERT @retContactInformation 
    SELECT @BusinessEntityID, @FirstName, @LastName, @ContactType; 
END; 

RETURN; 
END; 
GO 
+1

當客戶不存在時,您想要返回什麼?沒有行NULL?其他一些價值? –

+0

您是否需要設置一個變量,如代碼示例中,或者是查詢中的CASE語句? –

+2

爲什麼我們需要猜測這個問題? –

回答

1

不知道你的代碼的其餘部分看起來像,但通常這將是:

SELECT name = COALESCE(c.customer_name, o.other_entity_name) 
    FROM dbo.MainEntity AS m 
    LEFT OUTER JOIN dbo.Customers AS c ON m.something = c.something 
    LEFT OUTER JOIN dbo.OtherTable AS o ON m.something = o.something; 

但是比一般的想法外,你沒有給相當足夠的信息來提供一個完整的回答。

+0

我不認爲有必要知道這裏給出的例子之外的任何東西。但是你的提問絕對有幫助,並給出了另一個見解謝謝 – WorkerThread