我可以在脚本或存储过程中创build一次性使用function吗?

在SQL Server 2005中,是否有一个一次性使用的概念,或在SQL脚本或存储过程中声明的本地函数? 我想在我正在编写的脚本中抽象出一些复杂性,但是它需要能够声明一个函数。

只是好奇。 谢谢!!

你可以在脚本开始附近调用CREATE Function ,在结尾处调用DROP Function

您可以创build临时存储过程,如:

 create procedure #mytemp as begin select getdate() into #mytemptable; end 

在一个SQL脚本中,但不是function。 你可以让proc将结果保存在临时表中,然后在脚本中使用这些信息。

公用表expression式允许您定义什么是基本上只在select,插入,更新和删除语句范围内的视图。 取决于你需要做什么,他们可以非常有用。

我知道我可能因为build议dynamicSQL而受到批评,但有时这是一个很好的解决scheme。 在考虑这一点之前,请确保您了解安全含义。

 DECLARE @add_a_b_func nvarchar(4000) = N'SELECT @c = @a + @b;'; DECLARE @add_a_b_parm nvarchar(500) = N'@a int, @b int, @c int OUTPUT'; DECLARE @result int; EXEC sp_executesql @add_a_b_func, @add_a_b_parm, 2, 3, @c = @result OUTPUT; PRINT CONVERT(varchar, @result); -- prints '5' 

在脚本中,你有更多的select和理性分解更好的select。 查看SQLCMD模式(查询菜单 – > SQLCMD模式),具体为:setvar和:r命令。

在存储过程中,您的选项非常有限。 您不能直接使用过程的主体来创build定义函数。 你可以做的最好的就是像这样的dynamicSQL:

 create proc DoStuff as begin declare @sql nvarchar(max) /* define function here, within a string note the underscore prefix, a good convention for user-defined temporary objects */ set @sql = ' create function dbo._object_name_twopart (@object_id int) returns nvarchar(517) as begin return quotename(object_schema_name(@object_id))+N''.''+ quotename(object_name(@object_id)) end ' /* create the function by executing the string, with a conditional object drop upfront */ if object_id('dbo._object_name_twopart') is not null drop function _object_name_twopart exec (@sql) /* use the function in a query */ select object_id, dbo._object_name_twopart(object_id) from sys.objects where type = 'U' /* clean up */ drop function _object_name_twopart end go 

如果存在这样的事物,这近似于全局临时function。 其他用户仍然可以看到它。 您可以附加连接的@@ SPID以使名称唯一,但是这会要求过程的其余部分也使用dynamicSQL。

以下是我用过去在MS SQL中完成对Scalar UDF的需求:

 IF OBJECT_ID('tempdb..##fn_Divide') IS NOT NULL DROP PROCEDURE ##fn_Divide GO CREATE PROCEDURE ##fn_Divide (@Numerator Real, @Denominator Real) AS BEGIN SELECT Division = CASE WHEN @Denominator != 0 AND @Denominator is NOT NULL AND @Numerator != 0 AND @Numerator is NOT NULL THEN @Numerator / @Denominator ELSE 0 END RETURN END GO Exec ##fn_Divide 6,4 

这种为PROCEDURE使用全局variables的方法,不仅可以在脚本中使用该函数,还可以在dynamicSQL需求中使用该函数。