使用'AS'语句在SQL Server中创建函数 [英] Usage of 'AS' statement to create functions in SQL Server

查看:157
本文介绍了使用'AS'语句在SQL Server中创建函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建函数时是否必须使用AS语句。几乎包括MSDN的每个示例在创建函数时都使用AS语句。来自MSDN,





但实际上我可以在不使用AS语句的情况下创建一个函数并且它可以工作。


那么为什么我们使用AS语句来创建函数,尽管它没有它的工作吗?第二个问题是,我尝试了相同的存储过程的情况,并意识到它是强制性的使用AS语句。是真的,AS的使用对于创建存储过程是强制性的,但对于创建函数是不可或缺的。 解析方法

a href =http://msdn.microsoft.com/en-us/library/ms186755.aspx =nofollow>官方文档

< pre-class =lang-sql prettyprint-override> - Transact-SQL标量函数语法
CREATE FUNCTION [schema_name。 ] function_name
([{@parameter_name [AS] [type_schema_name。] parameter_data_type
[= default] [READONLY]}
[,... n]
]

RETURNS return_data_type
[WITH< function_option> [,... n]]
[AS]
BEGIN
function_body
RETURN scalar_expression
END
[; ]

请注意,使用 AS 是这里可选。 (请参阅 Transact-SQL语法约定(Transact-SQL)) p>

是的,当创建 AS 是必需的-us / library / ms187926.aspxrel =nofollow>存储过程,但不能在创建函数时使用。这只是关于该语言的许多怪癖之一。

我个人比较喜欢用 AS 来创建函数,因为它更像风格清楚地将函数的签名与正文分开,并且使语法与创建存储过程的语法更加一致(即使语言不需要它)。

Is it mandatory to use AS statement when creating functions. Almost every example including MSDN uses AS statement while creating function. From MSDN,

But actually I can create a function without using AS statement and it works.

So why we are using AS statement for creating functions, although it works without it?

The second question is that, I tried the same scenario for stored procedures and realized that it is mandatory to use AS statement. Is it true that, usage of AS is mandatory for creating stored procedure but not for creating functions.

解决方案

The syntax from the official documentation is

--Transact-SQL Scalar Function Syntax
CREATE FUNCTION [ schema_name. ] function_name 
( [ { @parameter_name [ AS ][ type_schema_name. ] parameter_data_type 
    [ = default ] [ READONLY ] } 
    [ ,...n ]
  ]
)
RETURNS return_data_type
    [ WITH <function_option> [ ,...n ] ]
    [ AS ]
    BEGIN 
        function_body 
        RETURN scalar_expression
    END
[ ; ]

Notice that the use of AS is optional here. (See Transact-SQL Syntax Conventions (Transact-SQL))

And yes, AS is required when creating stored procedures, but not when creating functions. This is just one of the many quirks about the language.

I personally prefer to use AS whenever I'm creating functions it as a matter of style, because it more clearly separates the signature of the function from the body, and it makes the syntax more consistent with the syntax for creating stored procedures (even if the language doesn't require it).

这篇关于使用'AS'语句在SQL Server中创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆