We have some views and stored procedures which have some data hard-coded in their definitions.
CASE WHEN sprLatestSPR2.StatusID IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20)
I create a table that holds all global variables. For example, I define STATUS_SET1 to 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20 in the table.
Now I need to write a script to replace all hard-coded data in the definitions of views & store procedures with queries. For example I need replace above clause with
CASE WHEN sprLatestSPR2.StatusID IN (SELECT STATUS_SET1 FROM myGlobalVariables)
How do I write a script to search the definitions of the views & stored procedures and do the replacement?
Update:
I have the query to find out the first part of my question, search the definition of view/store procedure for a specific sentence.
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(object_id) LIKE '%StatusID<21%'
Now my question is how to update view/store procedure to replace all the occurrences of StatusID<21 with some global variable?
New Update:
I run following script in the SSMS,
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(object_id) LIKE ‘%V.EmailStatus=”GP”%’
SELECT STUFF(REPLACE(definition, ‘V.EmailStatus=”GP”’, ‘V.EmailStatus=”RL”’), 1, 6, ‘ALTER’)
+ CHAR(13) + CHAR(10) + ‘GO’
FROM sys.sql_modules WHERE definition LIKE ‘%V.EmailStatus=”GP”%’
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(object_id) LIKE ‘%V.EmailStatus=”GP”%’
I got the same result from the third SELECT as the first SELECT, which is should be nothing, since I replaced GP with RL.
Assuming the procedure starts with
CREATEexactly, you can say:If it can have leading spaces, comments before
CREATE, etc. then it can get a bit more complex.You can also just return the scripts themselves, or script them out to files, then do your own search and replace within SSMS or your favorite text editor.
EDIT note that this will just produce the script to alter your objects. You’ll want to verify them, backup your database first, then copy the script and run it.
EDIT 2 explaining code based on question
sys.sql_modules.definitioncontains aCREATEscript that represents your procedure/function body. It does not include theGOrequired between altering modules, nor is there a way to have it output anALTERcommand instead (I’ve asked for it in the past but I’ll have to agree with them I’d rather seeCREATE OR REPLACEsyntax).STUFFin this case takes the output (which will beCREATE PROCEDURE ...after the1, 2, ...has been replaced) and, starting with the first character, replaces the first 6 characters (CREATE) withALTER– since the assumption is that you will want to run these as alters as opposed to drop / create (so that you don’t lose permissions / dependencies).The
GOadds a batch separator between each body, sinceALTER PROCEDUREmust be in its own batch. So instead of……which will generate errors, you’ll have…
…which will ensure that each stored procedure is handled in its own batch.