Creating a User Defined function in Stored Procedure in SQL 2005

邮差的信 提交于 2019-12-12 18:36:17

问题


I have a stored procedure in which i want to create a user defined function - Split (splits a string separated with delimiters and returns the strings in a table), make use of the function and finally drop the function.

My question is that whether i can create a user defined function inside a stored procedure and drop it finally?

Thank you.

Regards NLV


回答1:


Technically...yes you could but that does not mean you should. You would have to be careful about avoiding GO statements (just use Exec for each batch) but you could do something like:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE dbo.Test
AS

Declare @Sql nvarchar(max)

Set @Sql = 'CREATE FUNCTION dbo.Foo
(   
)
RETURNS TABLE 
AS
RETURN 
(
    SELECT 0 As Bar
)'

Exec(@Sql)

Select * 
From dbo.Foo()


Set @Sql = 'Drop Function dbo.Foo'
Exec(@Sql)

Return
GO
Exec dbo.Test

That said, I would strongly recommend against this sort of solution, especially if the function you want is something that would be useful like a Split function. I would recommend just creating the UDF and using it and leaving it until you might use it again.




回答2:


CTEs would be good here too, depending on what your UDF is trying to do.



来源:https://stackoverflow.com/questions/2505408/creating-a-user-defined-function-in-stored-procedure-in-sql-2005

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!