4

我想从我定义如下的函数返回一个简单的 varchar 值:

CREATE FUNCTION getCustomerType (@orderNumber INT)
    RETURNS VARCHAR(30)
AS
Return 
    (
    select custtype from Customer c 
        join order o on o.customerid =  c.customerid
    where o.orderNumber = @orderNumber 
 )
GO

select getCustType(1063609) 

应该返回下订单的客户类型#1063609 但失败

4

1 回答 1

10

我会将您的函数的语法更改为以下内容:

CREATE FUNCTION dbo.getCustomerType (@orderNumber INT)
    RETURNS VARCHAR(30)
AS
begin
  declare @custtype varchar(30)
  SET @custtype = (select custtype 
                      from dbo.Customer c 
                      join dbo.[order] o 
                        on o.customerid =  c.customerid
                      where o.orderNumber = @orderNumber)

  return @custtype
end 

然后,当您使用架构(dbo.如下)调用该函数时,您将使用:

select dbo.getCustomerType(10636909)

请参阅带有演示的 SQL Fiddle

该函数也可以写成(感谢@MartinSmith):

CREATE FUNCTION getCustomerType (@orderNumber INT)
    RETURNS VARCHAR(30)
AS
begin
  return (select custtype 
                      from dbo.Customer c 
                      join dbo.[order] o 
                        on o.customerid =  c.customerid
                      where o.orderNumber = @orderNumber)
end 

请参阅带有演示的 SQL Fiddle

于 2013-02-21T17:06:57.347 回答