问题
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