Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从自定义T-SQL函数返回Varchar_Sql_Sql Server_Tsql_Function - Fatal编程技术网

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

从自定义T-SQL函数返回Varchar,sql,sql-server,tsql,function,Sql,Sql Server,Tsql,Function,我想从我定义如下的函数返回一个简单的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

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

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

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)

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


请参见

您需要对函数调用进行架构限定。失败是什么意思?“getCustType”不是可识别的函数名。=失败请使用
dbo.getCustType
或任何正确的架构。如果函数创建为
getCustomerType
,为什么要调用
getCustType
?您不能只执行
从..
中选择t@custtype=custtype吗?更容易,我想…@marc_s是的,我只是想在我的例子中描述一下。@AaronBertrand谢谢你的编辑,我是根据sql fiddle写的……显然我没有思考……)<代码>返回(选择…不需要中间变量,但看起来像
开始。。。即使对于单语句标量UDF,END
也是必需的,因此OP应该有另一个错误,他们没有告诉我们。@Martin yes
BEGIN/END
是标量函数所必需的,直到我们有内联标量函数为止。
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