Domanda

I'm stuck trying to create a function to display customer names based on area code.

Function is created, but I'm getting null results for known area codes where I should be getting lots.

I'm a clueless newbie, and that may be a factor.

alter function ufnGetCustomerByAreaCode(@AreaCode nvarchar(3))
returns nvarchar(100)
as
begin
declare @Customer as nvarchar(100);
set @Customer =
    (
        select c.FirstName + ' ' + c.LastName
        from SalesLT.Address as a
        join SalesLT.CustomerAddress as ca
        on a.AddressID = ca.AddressID
        join SalesLT.Customer as c
        on ca.CustomerID = c.CustomerID
        where left(a.PostalCode,3) = @AreaCode
    )
    return @Customer
    end

Using the command

select dbo.ufnGetCustomerByAreaCode(706)

I'm getting null results. The table has lots of 706 area codes.

È stato utile?

Soluzione

You are filtering on left 3 chars of PostalCode (a.k.a. zip code), I think you meant to use left 3 chars of Phone Number instead since that is where you find the area code.

Also, you have created a scalar function, so after you change to filter on area code instead of postal code, and if there is more than one customer with the 706 area code, you will likely get the following error:

"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."

If you are wanting to retrieve all customers that have a certain area code, then you will need a table value function. See http://technet.microsoft.com/en-us/library/ms189294(v=sql.105).aspx

If you do not want duplicate customer names returned, then add DISTINCT after the SELECT in your function.

Note that when selecting from a table valued function, you should use the syntax

SELECT Customers FROM dbo.ufnGetCustomerByAreaCode('706') 

instead of

SELECT dbo.ufnGetCustomerByAreaCode('706')
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top