从自定义 T-SQL 函数返回 Varchar

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15008007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:49:01  来源:igfitidea点击:

Return Varchar from Custom T-SQL Functions

sqlsql-servertsqlfunction

提问by devved

i would like to return a simple varchar value from a function that i define as follow :

我想从我定义如下的函数返回一个简单的 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) 

supposed to return customer type of customer who made order#1063609 but fails

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

回答by Taryn

I would alter the syntax of your function to the following:

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

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 

Then when you call the function using the schema (dbo.below), you will use:

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

select dbo.getCustomerType(10636909)

See SQL Fiddle with Demo

参见SQL Fiddle with Demo

The function can also be written as (thanks @MartinSmith):

该函数也可以写成(感谢@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 

See SQL Fiddle with Demo

参见SQL Fiddle with Demo