使用变量删除Sql函数作为函数名

时间:2016-08-01 11:14:40

标签: sql-server function

我想删除模式中的所有函数,我不想写一些要求我提前获取所有函数名并在SQL中编写的东西

DROP FUNCTION MySchema.FunctionName1
DROP FUNCTION MySchema.FunctionName2
... etc

我试过了:

DECLARE @FuncName varchar(100)

WHILE (SELECT Count(*) From information_schema.routines 
         WHERE SPECIFIC_SCHEMA = 'MySchema' AND ROUTINE_TYPE = 'function') > 0
BEGIN
    SELECT top(1) @FuncName = ROUTINE_NAME FROM information_schema.routines
       WHERE SPECIFIC_SCHEMA = 'MySchema' AND ROUTINE_TYPE = 'function'

    BEGIN
        DROP FUNCTION @FuncName  -- it doesn't like it because it is a string variable
    END     

END

sql script to drop old versions of stored procedures and functions 有点类似,但只是像第一个例子一样生成SQL而实际上并没有运行它

2 个答案:

答案 0 :(得分:3)

试试这个动态的sql,

DECLARE @FuncName nvarchar(500)

WHILE (SELECT Count(*) From information_schema.routines 
         WHERE SPECIFIC_SCHEMA = 'MySchema' AND ROUTINE_TYPE = 'function') > 0
BEGIN
    SELECT top(1) @FuncName = 'DROP FUNCTION ' + SPECIFIC_SCHEMA + '.' + ROUTINE_NAME FROM information_schema.routines
       WHERE SPECIFIC_SCHEMA = 'MySchema' AND ROUTINE_TYPE = 'function'

    BEGIN
        EXEC (@FuncName)  -- it doesn't like it because it is a string variable
    END     

END

此外,您可以使用以下功能一次性删除所有功能

DECLARE @FuncName nvarchar(MAX) = ''

SELECT @FuncName = @FuncName + 'DROP FUNCTION ' + SPECIFIC_SCHEMA + '.' + ROUTINE_NAME + CHAR(10) 
FROM information_schema.routines
WHERE SPECIFIC_SCHEMA = 'MySchema' AND ROUTINE_TYPE = 'function'

EXEC sp_executesql @FuncName

答案 1 :(得分:0)

根据Jatin Patel的回答我需要知道动态sql位! (这可能是一个注释,但stackoverflow无法处理@符号) 我使用以下版本来提高可读性,而@FuncName保留了它的原始含义

DECLARE @FuncName varchar(100)

WHILE (SELECT COUNT(*) 
       FROM information_schema.routines 
       WHERE SPECIFIC_SCHEMA = 'MySchema' AND ROUTINE_TYPE = 'function' ) > 0
BEGIN
    SELECT TOP(1) @FuncName = ROUTINE_NAME
    FROM information_schema.routines
    WHERE SPECIFIC_SCHEMA = 'MySchema' AND ROUTINE_TYPE = 'function'

    BEGIN
        EXEC ('DROP FUNCTION MySchema.' + @FuncName)
    END     

END