sql script to drop old versions of stored procedures and functions

半城伤御伤魂 提交于 2019-12-10 11:56:21

问题


I am looking to write a sql server script to achieve the following in a sql server 2008 database.

I have a number of functions and stored procedures with the following names:

  • prSP_GetItem.1.0.0
  • prSP_GetItem.1.1.0
  • prSp_GetItem.1.2.0

As you can see a version number is appended to them.

Each time a new version of the application is released, new functions/stored procedures are created with the new version number.

What I would like to do is write a generic script to remove all old version of a function or stored procedures. So lets say current version is 1.2.0, all functions and stored procedures ending in a version number before this eg. 1.0.0, 1.1.1 etc should be dropped.

Any tips or ideas how I might write a script to achieve this?


回答1:


You can use this as starting point and see how far it can take you. Run it against your DB and post your observations. The last select only lists the SQL statement in the last column. Nothing gets executed actually. Verify the output very carefully.

;With RawData As
(
    SELECT
          name
        , SUBSTRING(name, 1, CHARINDEX('.', name) - 1) AS BaseName
        , CAST(REPLACE(SUBSTRING(name, CHARINDEX('.', name), LEN(name) - CHARINDEX('.', name) + 1), '.', '') AS INT) AS IntVersion
    FROM
        sys.objects
    WHERE
        type = 'P'
        AND
        CHARINDEX('.', name) > 0
        AND
        ISNUMERIC(REPLACE(SUBSTRING(name, CHARINDEX('.', name), LEN(name) - CHARINDEX('.', name) + 1), '.', '')) = 1
)
,GroupedData As
(
    SELECT
          BaseName
        , MAX(CAST(REPLACE(SUBSTRING(name, CHARINDEX('.', name), LEN(name) - CHARINDEX('.', name) + 1), '.', '') AS INT)) AS IntVersion
    FROM
        RawData
    GROUP BY
        BaseName
)
SELECT
    *
    , NULLIF(ISNULL(GD.BaseName, ''), ISNULL(GD.BaseName, '-')) + 'DROP PROCEDURE [' + Name + ']' as SQLs
FROM
    RawData RD
LEFT JOIN
    GroupedData GD
ON
    RD.BaseName = GD.BaseName
    AND
    RD.IntVersion = GD.IntVersion
--WHERE
--  GD.BaseName IS NULL
ORDER BY
      RD.BaseName
    , RD.IntVersion


来源:https://stackoverflow.com/questions/7576739/sql-script-to-drop-old-versions-of-stored-procedures-and-functions

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