2016-08-01 52 views
0

我想刪除模式中的所有函數,並且我不想寫一些需要我提前獲取所有函數名稱的東西,並將其寫入SQL將變量作爲函數名刪除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像第一個例子,並不實際運行

+0

你正在尋找的技術被稱爲[動態SQL](https://msdn.microsoft.com/en-us/library/ms709342(v = vs.85).aspx)。請特別小心,以確保[動態代碼安全](https://msdn.microsoft.com/zh-cn/library/bb669091(v = vs.110).aspx)。此技術可以打開[SQL注入漏洞](https://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx)。 –

+0

除非一個函數已經被放到數據庫(由授權或未授權的人),並且它被稱爲「MySchema.FunctionName GO DROP TABLE用戶」或者一些同樣荒謬的東西,我沒有看到那個評論試圖告訴我什麼 – ono2012

回答

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

你也可以寫這個沒有循環。只要確保你的drop語句是'GO'分隔的並且動態查詢變量足夠大。 –

0

關閉Jatin Patel的答案,我需要知道動態sql位! (這本來是一個註釋,但計算器不能用@符號應付) 我用下面的版本可讀性和@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