How to Check all stored procedure is ok in sql server? - sql

How to check all stored procedure is ok in sql server if I drop a table or fields?

I found Cade's answer useful in formulating my own script for checking objects in a database, so I thought I'd share my script as well:
DECLARE #Name nvarchar(1000);
DECLARE #Sql nvarchar(1000);
DECLARE #Result int;
DECLARE ObjectCursor CURSOR FAST_FORWARD FOR
SELECT QUOTENAME(SCHEMA_NAME(o.schema_id)) + '.' + QUOTENAME(OBJECT_NAME(o.object_id))
FROM sys.objects o
WHERE type_desc IN (
'SQL_STORED_PROCEDURE',
'SQL_TRIGGER',
'SQL_SCALAR_FUNCTION',
'SQL_TABLE_VALUED_FUNCTION',
'SQL_INLINE_TABLE_VALUED_FUNCTION',
'VIEW')
--include the following if you have schema bound objects since they are not supported
AND ISNULL(OBJECTPROPERTY(o.object_id, 'IsSchemaBound'), 0) = 0
;
OPEN ObjectCursor;
FETCH NEXT FROM ObjectCursor INTO #Name;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #Sql = N'EXEC sp_refreshsqlmodule ''' + #Name + '''';
--PRINT #Sql;
BEGIN TRY
EXEC #Result = sp_executesql #Sql;
IF #Result <> 0 RAISERROR('Failed', 16, 1);
END TRY
BEGIN CATCH
PRINT 'The module ''' + #Name + ''' does not compile.';
IF ##TRANCOUNT > 0 ROLLBACK TRANSACTION;
END CATCH
FETCH NEXT FROM ObjectCursor INTO #Name;
END
CLOSE ObjectCursor;
DEALLOCATE ObjectCursor;

It won't catch everything (dynamic SQL or latebound objects), but it can be useful - call sp_refreshsqlmodule on all non-schema bound stored procedures (you can call it before to ensure that dependencies are updated and then query the dependencies, or call it afterwards and see if anything is broken):
DECLARE #template AS varchar(max)
SET #template = 'PRINT ''{OBJECT_NAME}''
EXEC sp_refreshsqlmodule ''{OBJECT_NAME}''
'
DECLARE #sql AS varchar(max)
SELECT #sql = ISNULL(#sql, '') + REPLACE(#template, '{OBJECT_NAME}',
QUOTENAME(ROUTINE_SCHEMA) + '.'
+ QUOTENAME(ROUTINE_NAME))
FROM INFORMATION_SCHEMA.ROUTINES
WHERE OBJECTPROPERTY(OBJECT_ID(QUOTENAME(ROUTINE_SCHEMA) + '.'
+ QUOTENAME(ROUTINE_NAME)),
N'IsSchemaBound') IS NULL
OR OBJECTPROPERTY(OBJECT_ID(QUOTENAME(ROUTINE_SCHEMA) + '.'
+ QUOTENAME(ROUTINE_NAME)),
N'IsSchemaBound') = 0
EXEC (
#sql
)

In addition to the script from Michael Petito you can check for issues with late-bound objects in SPs (deferred name resolution) like this:
-- Based on comment from http://blogs.msdn.com/b/askjay/archive/2012/07/22/finding-missing-dependencies.aspx
-- Check also http://technet.microsoft.com/en-us/library/bb677315(v=sql.110).aspx
select o.type, o.name, ed.referenced_entity_name, ed.is_caller_dependent
from sys.sql_expression_dependencies ed
join sys.objects o on ed.referencing_id = o.object_id
where ed.referenced_id is null

I basically did the same thing, but wrote it to be CURSORless which is super fast.
DECLARE #Name nvarchar(1000);
DECLARE #Sql nvarchar(1000);
DECLARE #Result int;
DECLARE #Objects TABLE (
Id INT IDENTITY(1,1),
Name nvarchar(1000)
)
INSERT INTO #Objects
SELECT QUOTENAME(SCHEMA_NAME(o.schema_id)) + '.' + QUOTENAME(OBJECT_NAME(o.object_id))
FROM sys.objects o
WHERE type_desc IN (
'SQL_STORED_PROCEDURE',
'SQL_TRIGGER',
'SQL_SCALAR_FUNCTION',
'SQL_TABLE_VALUED_FUNCTION',
'SQL_INLINE_TABLE_VALUED_FUNCTION',
'VIEW')
--include the following if you have schema bound objects since they are not supported
AND ISNULL(OBJECTPROPERTY(o.object_id, 'IsSchemaBound'), 0) = 0
DECLARE #x INT
DECLARE #xMax INT
SELECT #xMax = MAX(Id) FROM #Objects
SET #x = 1
WHILE #x < #xMax
BEGIN
SELECT #Name = Name FROM #Objects WHERE Id = #x
SET #Sql = N'EXEC sp_refreshsqlmodule ''' + #Name + '''';
--PRINT #Sql;
BEGIN TRY
EXEC #Result = sp_executesql #Sql;
IF #Result <> 0 RAISERROR('Failed', 16, 1);
END TRY
BEGIN CATCH
PRINT 'The module ''' + #Name + ''' does not compile.';
IF ##TRANCOUNT > 0 ROLLBACK TRANSACTION;
END CATCH
SET #x = #x + 1
END

Couple of ways that come to mind
Most obvious way run the procedures
check dependencies on the table before you drop the table or a field. then check out those dependent proceudres
generate scripts on all procedures and search for that field or table
Query sysobjects

Once I made change to a table such as column rename, I have to alter all the stored procedures, functions and views that refer the table column. Obviously I have to manually alter them one by one. But my database contains hundreds of objects like these. So I wanted to make sure I have altered all the depending objects. One solution is to recompile all the objects (via a script). But recompilation happens on each object’s next execution only. But what I want is to validate them and get the details now.
For that I can use “sp_refreshsqlmodule” instead of “sp_recompile”. This will refresh each object and throws an error if its not parsing correctly.
Here is the script below;
-- table variable to store procedure names
DECLARE #tblObjects TABLE (ObjectID INT IDENTITY(1,1), ObjectName
sysname)
-- get the list of stored procedures, functions and views
INSERT INTO #tblObjects(ObjectName)
SELECT '[' + sc.[name] + '].[' + obj.name + ']'
FROM sys.objects obj
INNER JOIN sys.schemas sc ON sc.schema_id = obj.schema_id
WHERE obj.[type] IN ('P', 'FN', 'V') -- procedures, functions, views
-- counter variables
DECLARE #Count INT, #Total INT
SELECT #Count = 1
SELECT #Total = COUNT(*) FROM #tblObjects
DECLARE #ObjectName sysname
-- start the loop
WHILE #Count <= #Total BEGIN
SELECT #ObjectName = ObjectName
FROM #tblObjects
WHERE ObjectID = #Count
PRINT 'Refreshing... ' + #ObjectName
BEGIN TRY
-- refresh the stored procedure
EXEC sp_refreshsqlmodule #ObjectName
END TRY
BEGIN CATCH
PRINT 'Validation failed for : ' + #ObjectName + ', Error:' +
ERROR_MESSAGE() + CHAR(13)
END CATCH
SET #Count = #Count + 1
END
If any object throws an error I can now attend to it and manually fix the issue with it.

None of the answers given can find the error resulting from renaming or dropping a table
but be happy, I have a solution on SQL Server 2017 and higher versions:
DECLARE #NumberRecords INT
DECLARE #RowCount INT
DECLARE #Name NVARCHAR(MAX)
DECLARE #Command NVARCHAR(MAX)
DECLARE #Result int
DECLARE #Names TABLE (
[RowId] INT NOT NULL IDENTITY(1, 1),
[Name] NVARCHAR(MAX),
[Type] NVARCHAR(MAX)
)
INSERT INTO #Names
SELECT
QUOTENAME(SCHEMA_NAME([Objects].schema_id)) + '.' + QUOTENAME(OBJECT_NAME([Objects].object_id)) [Name],
type_desc [Type]
FROM sys.objects [Objects]
WHERE type_desc IN ('SQL_STORED_PROCEDURE',
'SQL_TRIGGER',
'SQL_SCALAR_FUNCTION',
'SQL_TABLE_VALUED_FUNCTION',
'SQL_INLINE_TABLE_VALUED_FUNCTION',
'VIEW')
ORDER BY [Name]
SET #RowCount = 1
SET #NumberRecords = (SELECT COUNT(*) FROM #Names)
WHILE (#RowCount <= #NumberRecords)
BEGIN
SELECT #Name = [Name]
FROM #Names
WHERE [RowId] = #RowCount
SET #Command = N'EXEC sp_refreshsqlmodule ''' + #Name + ''''
BEGIN TRY
EXEC #Result = sp_executesql #Command
IF #Result <> 0
BEGIN
RAISERROR('Failed', 16, 1)
END
ELSE
BEGIN
IF (NOT EXISTS (SELECT *
FROM sys.dm_sql_referenced_entities(#Name, 'OBJECT')
WHERE [is_incomplete] = 1))
BEGIN
DELETE
FROM #Names
WHERE [RowId] = #RowCount
END
END
END TRY
BEGIN CATCH
-- Nothing
END CATCH
SET #RowCount = #RowCount + 1
END
SELECT [Name],
[Type]
FROM #Names

I tried "Cade Roux" Answer , it went wrong and I fixed it as following
SELECT 'BEGIN TRAN T1;' UNION
SELECT REPLACE('BEGIN TRY
EXEC sp_refreshsqlmodule ''{OBJECT_NAME}''
END TRY
BEGIN CATCH
PRINT ''{OBJECT_NAME} IS INVALID.''
END CATCH', '{OBJECT_NAME}',
QUOTENAME(ROUTINE_SCHEMA) + '.'
+ QUOTENAME(ROUTINE_NAME))
FROM INFORMATION_SCHEMA.ROUTINES
WHERE OBJECTPROPERTY(OBJECT_ID(QUOTENAME(ROUTINE_SCHEMA) + '.'
+ QUOTENAME(ROUTINE_NAME)),
N'IsSchemaBound') IS NULL
OR OBJECTPROPERTY(OBJECT_ID(QUOTENAME(ROUTINE_SCHEMA) + '.'
+ QUOTENAME(ROUTINE_NAME)),
N'IsSchemaBound') = 0
UNION
SELECT 'ROLLBACK TRAN T1;'

Same idea, but more universal - you check all user defined objects with bodies
And it shows you error during compiling. This is really useful after renaming/removing objects/columns etc
Just run it after database schema update to make sure that all body objects still valid
DECLARE #obj_name AS sysname, #obj_type AS sysname
DECLARE obj_cursor CURSOR FOR
SELECT SCHEMA_NAME(o.schema_id) + '.' + o.name, o.type_desc
FROM sys.objects o
INNER JOIN sys.sql_modules m ON o.object_id = m.object_id
WHERE o.is_ms_shipped = 0 AND m.is_schema_bound = 0
ORDER BY o.type_desc, SCHEMA_NAME(o.schema_id), o.name
OPEN obj_cursor
FETCH NEXT FROM obj_cursor INTO #obj_name, #obj_type
WHILE (##FETCH_STATUS <> -1)
BEGIN
BEGIN TRY
EXEC sp_refreshsqlmodule #obj_name
--PRINT 'Refreshing ''' + #obj_name + ''' completed'
END TRY
BEGIN CATCH
PRINT 'ERROR - ' + #obj_type + ' ''' + #obj_name + ''':' + ERROR_MESSAGE()
END CATCH
FETCH NEXT FROM obj_cursor INTO #obj_name, #obj_type
END
CLOSE obj_cursor
DEALLOCATE obj_cursor

My approach was a little bit different. I've created alter script for a bunch of procs in SSMS and then waited for few seconds so SSMS process them and Ive got what I wanted:
O then SSMS right border a red dot for any line in error, which I can easily check, correct and later execute same script to update with correct values.

Related

Dynamic / parametrized stored procedure in SQL Server [duplicate]

I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END

How to Grant Execute All Functions In SQL Server to group

I have a list of function I need to grant execute to specific group, I found that the query should be executed like this
GRANT EXECUTE ON [dbo].[FunctionName] TO [GroupName]
But since I have 40 functions in the database, so I need to execute it 40 times with updateing the finction name. And when I haave new unctions I need to execute the new one the same way, my question if there is a Script/Function that get all the functions name in the database and execute all just once. I am able to get the list of functions with this code:
SELECT name AS function_name
FROM sys.objects
WHERE type_desc LIKE '%FUNCTION%'
and also I create a function to execute it:
ALTER function [dbo].[listFunction]()
returns int
AS
BEGIN
declare #Result int;
declare #ListFn nvarchar(100);
set #ListFn = (
SELECT name AS function_name
FROM sys.objects
WHERE type_desc LIKE '%FUNCTION%'
);
if #ListFn=null
set #Result = 1
else
set #Result = 0
return #Result
end
but what is missing how to iterate each function and grant execute, so any help?
Edit: I have edited the query with this using the chema
DECLARE #SchemaName varchar(max)
DECLARE #GroupName varchar(max)
SET #SchemaName = 'dbo'
SET #GroupName = '[groupname]'
select 'GRANT EXECUTE ON OBJECT::' + #SchemaName + '.' + P.name + ' to ' + #GroupName
from sys.objects P
inner join sys.schemas S on P.schema_id = S.schema_id
where S.name = #SchemaName
and P.type_desc LIKE '%FUNCTION%'
Edit 2: I craete a procedure to execute the grant, because it cnnot work with function, so I executed it and no execeptionsshown, but I don't knwo if it i right or not:
CREATE PROCEDURE ExecuteAllFunctions
AS
BEGIN
DECLARE #i int
declare #Result int;
declare #ListFn nvarchar(100);
DECLARE #a TABLE (fnct nvarchar(max))
DECLARE #SchemaName varchar(max)
--DECLARE #a TABLE (id uniqueidentifier)
DECLARE #GroupName varchar(max)
SET #SchemaName = 'dbo'
SET #GroupName = '[GroupName]'
INSERT INTO #a select 'GRANT EXECUTE ON OBJECT::' + #SchemaName + '.' + P.name + ' to ' + #GroupName
from sys.objects P
inner join sys.schemas S on P.schema_id = S.schema_id
where S.name = #SchemaName
and P.type_desc LIKE '%FUNCTION%'
--EXEC #ListFn
--SET #i = 1
--WHILE (#i <= (SELECT MAX(fnct) FROM #a))
-- BEGIN
-- set #ListFn = (select fnct from #a a where a.fnct=)
-- SET #i = #i + 1
-- END
--if #ListFn=null
--set #Result = 1
--else
--set #Result = 0
--return #Result
end

Getting a table name in a Stored Procedure and using it later [duplicate]

I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END

How to drop all stored procedures at once in SQL Server database?

Currently we use separate a drop statements for each stored procedure in the script file:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MySP]')
AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[MySP]
Is there a way to drop them all at once, or maybe in a loop?
I would prefer to do it this way:
first generate the list of stored procedures to drop by inspecting the system catalog view:
SELECT 'DROP PROCEDURE [' + SCHEMA_NAME(p.schema_id) + '].[' + p.NAME + '];'
FROM sys.procedures p
This generates a list of DROP PROCEDURE statements in your SSMS output window.
copy that list into a new query window, and possibly adapt it / change it and then execute it
No messy and slow cursors, gives you the ability to check and double-check your list of procedure to be dropped before you actually drop it
Something like (Found at Delete All Procedures from a database using a Stored procedure in SQL Server).
Just so by the way, this seems like a VERY dangerous thing to do, just a thought...
declare #procName varchar(500)
declare cur cursor
for select [name] from sys.objects where type = 'p'
open cur
fetch next from cur into #procName
while ##fetch_status = 0
begin
exec('drop procedure [' + #procName + ']')
fetch next from cur into #procName
end
close cur
deallocate cur
In the Object Explorer pane, select the Stored Procedures folder.
Press F7 (or from the main menu, choose View > Object Explorer Details).
Select all procedures except the System Table.
Press Delete button and select OK.
You can delete Tables or Views in the same manner.
create below stored procedure in your db(from which db u want to delete sp's)
then right click on that procedure - click on Execute Stored Procedure..
then click ok.
create Procedure [dbo].[DeleteAllProcedures]
As
declare #schemaName varchar(500)
declare #procName varchar(500)
declare cur cursor
for select s.Name, p.Name from sys.procedures p
INNER JOIN sys.schemas s ON p.schema_id = s.schema_id
WHERE p.type = 'P' and is_ms_shipped = 0 and p.name not like 'sp[_]%diagram%'
ORDER BY s.Name, p.Name
open cur
fetch next from cur into #schemaName,#procName
while ##fetch_status = 0
begin
if #procName <> 'DeleteAllProcedures'
exec('drop procedure ' + #schemaName + '.' + #procName)
fetch next from cur into #schemaName,#procName
end
close cur
deallocate cur
I think this is the simplest way:
DECLARE #sql VARCHAR(MAX)='';
SELECT #sql=#sql+'drop procedure ['+name +'];' FROM sys.objects
WHERE type = 'p' AND is_ms_shipped = 0
exec(#sql);
To get drop statements for all stored procedures in a database
SELECT 'DROP PROCEDURE' + ' '
+ F.NAME + ';'
FROM SYS.objects AS F where type='P'
DECLARE #sql VARCHAR(MAX)
SET #sql=''
SELECT #sql=#sql+'drop procedure ['+name +'];' FROM sys.objects
WHERE type = 'p' AND is_ms_shipped = 0
exec(#sql);
Try this, it work for me
DECLARE #spname sysname;
DECLARE SPCursor CURSOR FOR
SELECT SCHEMA_NAME(schema_id) + '.' + name
FROM sys.objects
WHERE type = 'P';
OPEN SPCursor;
FETCH NEXT FROM SPCursor INTO #spname;
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC('DROP PROCEDURE ' + #spname);
FETCH NEXT FROM SPCursor INTO #spname;
END
CLOSE SPCursor;
DEALLOCATE SPCursor;
DECLARE #DeleteProcCommand NVARCHAR(500)
DECLARE Syntax_Cursor CURSOR
FOR
SELECT 'DROP PROCEDURE ' + p.NAME
FROM sys.procedures p
OPEN Syntax_Cursor
FETCH NEXT FROM Syntax_Cursor
INTO #DeleteProcCommand
WHILE (##FETCH_STATUS = 0)
BEGIN
EXEC (#DeleteProcCommand)
FETCH NEXT FROM Syntax_Cursor
INTO #DeleteProcCommand
END
CLOSE Syntax_Cursor
DEALLOCATE Syntax_Cursor
Try this:
DECLARE #sql NVARCHAR(MAX) = N'';
SELECT #sql += N'DROP PROCEDURE dbo.'
+ QUOTENAME(name) + ';
' FROM sys.procedures
WHERE name LIKE N'spname%'
AND SCHEMA_NAME(schema_id) = N'dbo';
EXEC sp_executesql #sql;
ANSI compliant, without cursor
DECLARE #SQL national character varying(MAX)
SET #SQL= ''
SELECT #SQL= #SQL+ N'DROP PROCEDURE "' + REPLACE(SPECIFIC_SCHEMA, N'"', N'""') + N'"."' + REPLACE(SPECIFIC_NAME, N'"', N'""') + N'"; '
FROM INFORMATION_SCHEMA.ROUTINES
WHERE (1=1)
AND ROUTINE_TYPE = 'PROCEDURE'
AND ROUTINE_NAME NOT IN
(
'dt_adduserobject'
,'dt_droppropertiesbyid'
,'dt_dropuserobjectbyid'
,'dt_generateansiname'
,'dt_getobjwithprop'
,'dt_getobjwithprop_u'
,'dt_getpropertiesbyid'
,'dt_getpropertiesbyid_u'
,'dt_setpropertybyid'
,'dt_setpropertybyid_u'
,'dt_verstamp006'
,'dt_verstamp007'
,'sp_helpdiagrams'
,'sp_creatediagram'
,'sp_alterdiagram'
,'sp_renamediagram'
,'sp_dropdiagram'
,'sp_helpdiagramdefinition'
,'fn_diagramobjects'
,'sp_upgraddiagrams'
)
ORDER BY SPECIFIC_NAME
-- PRINT #SQL
EXEC(#SQL)
Without cursor, non-ansi compliant:
DECLARE #sql NVARCHAR(MAX) = N''
, #lineFeed NVARCHAR(2) = CHAR(13) + CHAR(10) ;
SELECT #sql = #sql + N'DROP PROCEDURE ' + QUOTENAME(SPECIFIC_SCHEMA) + N'.' + QUOTENAME(SPECIFIC_NAME) + N';' + #lineFeed
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
-- AND SPECIFIC_NAME LIKE 'sp[_]RPT[_]%'
AND ROUTINE_NAME NOT IN
(
SELECT name FROM sys.procedures WHERE is_ms_shipped <> 0
)
ORDER BY SPECIFIC_NAME
-- PRINT #sql
EXECUTE(#sql)
By mixing the cursor and system procedure, we would have a optimized solution, as follow:
DECLARE DelAllProcedures CURSOR
FOR
SELECT name AS procedure_name
FROM sys.procedures;
OPEN DelAllProcedures
DECLARE #ProcName VARCHAR(100)
FETCH NEXT
FROM DelAllProcedures
INTO #ProcName
WHILE ##FETCH_STATUS!=-1
BEGIN
DECLARE #command VARCHAR(100)
SET #command=''
SET #command=#command+'DROP PROCEDURE '+#ProcName
--DROP PROCEDURE #ProcName
EXECUTE (#command)
FETCH NEXT
FROM DelAllProcedures
INTO #ProcName
END
CLOSE DelAllProcedures
DEALLOCATE DelAllProcedures
ANSI compliant, without cursor
PRINT ('1.a. Delete stored procedures ' + CONVERT( VARCHAR(19), GETDATE(), 121));
GO
DECLARE #procedure NVARCHAR(max)
DECLARE #n CHAR(1)
SET #n = CHAR(10)
SELECT #procedure = isnull( #procedure + #n, '' ) +
'DROP PROCEDURE [' + schema_name(schema_id) + '].[' + name + ']'
FROM sys.procedures
EXEC sp_executesql #procedure
PRINT ('1.b. Stored procedures deleted ' + CONVERT( VARCHAR(19), GETDATE(), 121));
GO
Try this:
declare #procName varchar(500)
declare cur cursor
for SELECT 'DROP PROCEDURE [' + SCHEMA_NAME(p.schema_id) + '].[' + p.NAME + ']'
FROM sys.procedures p
open cur
fetch next from cur into #procName
while ##fetch_status = 0
begin
exec( #procName )
fetch next from cur into #procName
end
close cur
deallocate cur

How to rebuild view in SQL Server 2008

There is a view in my DB that someone defined with a * from one table. I just added a new column to that table and I want the view to reflect the new column. Besides re-executing the view creation script, is there another way to rebuild the view? I am looking for something similar to how sp_recompile will recompile a stored procedure (or more accurately flag it to be compiled next time it is called).
Update: On a long shot I tried calling sp_recompile on the view and while the call worked, it didn't rebuild the view.
Update 2: I would like to be able to do this from a script. So the script that adds the columns to the table could also update the view. So like I said, something similar to sp_recompile.
I believe what you're looking for is
sp_refreshview [ #viewname = ] 'viewname'
Updates the metadata for the specified
non-schema-bound view. Persistent
metadata for a view can become
outdated because of changes to the
underlying objects upon which the view
depends.
See Microsoft Docs
In order to rebuild all views of a SQL Server database, you could use the following script:
DECLARE #view_name AS NVARCHAR(500);
DECLARE views_cursor CURSOR FOR
SELECT TABLE_SCHEMA + '.' +TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'VIEW'
AND OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'IsMsShipped') = 0
ORDER BY TABLE_SCHEMA,TABLE_NAME
OPEN views_cursor
FETCH NEXT FROM views_cursor
INTO #view_name
WHILE (##FETCH_STATUS <> -1)
BEGIN
BEGIN TRY
EXEC sp_refreshview #view_name;
PRINT #view_name;
END TRY
BEGIN CATCH
PRINT 'Error during refreshing view "' + #view_name + '".';
END CATCH;
FETCH NEXT FROM views_cursor
INTO #view_name
END
CLOSE views_cursor;
DEALLOCATE views_cursor;
This is a slightly modified version from this blog posting. It uses the sp_refreshview stored procedure, too.
As well as Cory's answer, you could define it properly using schemabinding and the full column list.
CREATE VIEW MyView
WITH SCHEMABINDING
AS
SELECT
col1, col2, col3, ..., coln
FROM
MyTable
GO
Slightly modified script that refreshes all views, calls sp_recompile, sp_refresh and gets list from sys.views:
DECLARE #view_name AS NVARCHAR(500);
DECLARE views_cursor CURSOR FOR SELECT DISTINCT name from sys.views
OPEN views_cursor
FETCH NEXT FROM views_cursor
INTO #view_name
WHILE (##FETCH_STATUS <> -1)
BEGIN
BEGIN TRY
EXEC sp_recompile #view_name;
EXEC sp_refreshview #view_name;
PRINT #view_name;
END TRY
BEGIN CATCH
PRINT 'Error during refreshing view "' + #view_name + '".';
END CATCH;
FETCH NEXT FROM views_cursor
INTO #view_name
END
CLOSE views_cursor;
DEALLOCATE views_cursor;
sp_refreshview does not seem to be relyable! When I used the code from Uwe Keim/BogdanRB I got many errors even if the view has no invalid references! The following code did the trick for me (to determine which view is invalid after schema changes):
DECLARE #view_name AS NVARCHAR(500);
DECLARE #Query AS NVARCHAR(600);
SET #Query = '';
DECLARE views_cursor CURSOR FOR SELECT DISTINCT ('[' + SCHEMA_NAME(schema_id) + '].[' + name + ']') AS Name FROM sys.views
OPEN views_cursor
FETCH NEXT FROM views_cursor
INTO #view_name
WHILE (##FETCH_STATUS <> -1)
BEGIN
EXEC sp_recompile #view_name;
SELECT #Query = 'SELECT ''' + #view_name + ''' AS Name, COUNT(*) FROM ' + #view_name + ' AS Count; ';
EXEC (#Query);
-- PRINT #view_name;
FETCH NEXT FROM views_cursor
INTO #view_name
END
CLOSE views_cursor;
DEALLOCATE views_cursor;
Here is my favorite script for this (I modified an old sp_exec checking script I had), it uses EXEC sp_refreshsqlmodule #name
SET NOCOUNT ON;
-- Set ViewOnly to 1 to view missing EXECUTES. Set to 0 to correct missing EXECUTEs
DECLARE
#ViewOnly INT; SET #ViewOnly = 0;
-- Role to set execute permission on.
DECLARE
#ROLE sysname ; set #ROLE = QUOTENAME('spexec');
DECLARE
#ID INT,
#LAST_ID INT,
#NAME NVARCHAR(2000),
#SQL NVARCHAR(2000);
DECLARE #Permission TABLE (
id INT IDENTITY(1,1) NOT NULL,
spName NVARCHAR(2000),
object_type NVARCHAR(2000),
roleName NVARCHAR(2000),
permission NVARCHAR(2000),
state NVARCHAR(2000)
)
--Initialise the loop variable
SET #LAST_ID = 0
--Get all the stored procs into a temp table.
WHILE #LAST_ID IS NOT NULL
BEGIN
-- Get next lowest value
SELECT #ID = MIN(object_id)
FROM sys.objects
WHERE object_id > #LAST_ID
-- Looking for Stored Procs, Scalar, Table and Inline Functions
AND type IN ('P','FN','IF','TF','AF','FS','FT','PC', 'V')
SET #LAST_ID = #ID
IF #ID IS NOT NULL
BEGIN
INSERT INTO #Permission
SELECT o.name,
o.type_desc,
r.name,
p.permission_name,
p.state_desc
FROM sys.objects AS o
LEFT outer JOIN sys.database_permissions AS p
ON p.major_id = o.object_id
LEFT OUTER join sys.database_principals r
ON p.grantee_principal_id = r.principal_id
WHERE o.object_id = #ID
AND o.type IN ('P','FN','IF','TF','AF','FS','FT','PC', 'V')
--Exclude special stored procs, which start with dt_...
AND NOT o.name LIKE 'dt_%'
AND NOT o.name LIKE 'sp_%'
AND NOT o.name LIKE 'fn_%'
END
END
--GRANT the Permissions, only if the viewonly is off.
IF ISNULL(#ViewOnly,0) = 0
BEGIN
--Initialise the loop variable
SET #LAST_ID = 0
WHILE #LAST_ID IS NOT NULL
BEGIN
-- Get next lowest value
SELECT #ID = MIN(id)
FROM #Permission
WHERE roleName IS NULL
AND id > #LAST_ID
SET #LAST_ID = #ID
IF #ID IS NOT NULL
BEGIN
SELECT #NAME = spName
FROM #Permission
WHERE id = #ID
PRINT 'EXEC sp_refreshsqlmodule ' + #NAME
-- Build the DCL to do the GRANT
SET #SQL = 'sp_refreshsqlmodule [' + #NAME + ']'
-- Run the SQL Statement you just generated
EXEC (#SQL)
END
END
--Reselect the now changed permissions
SELECT o.name,
o.type_desc,
r.name,
p.permission_name,
p.state_desc
FROM sys.objects AS o
LEFT outer JOIN sys.database_permissions AS p
ON p.major_id = o.object_id
LEFT OUTER join sys.database_principals r
ON p.grantee_principal_id = r.principal_id
WHERE o.type IN ('P','FN','IF','TF','AF','FS','FT','PC', 'V')
AND NOT o.name LIKE 'dt_%'
AND NOT o.name LIKE 'sp_%'
AND NOT o.name LIKE 'fn_%'
ORDER BY o.name
END
ELSE
BEGIN
--ViewOnly: select the stored procs which need EXECUTE permission.
SELECT *
FROM #Permission
WHERE roleName IS NULL
END
Right-click on the view and choose Refresh from the popup menu?
You can use this sp:
CREATE PROCEDURE dbo.RefreshViews
#dbName nvarchar(100) = null
AS
BEGIN
SET NOCOUNT ON;
DECLARE #p nvarchar(250) = '#sql nvarchar(max) out'
DECLARE #q nvarchar(1000)
DECLARE #sql nvarchar(max)
if #dbName is null
select #dbName = DB_NAME()
SELECT #q = 'SELECT #sql = COALESCE(#sql + '' '', '''') + ''EXEC sp_refreshview ''''[' + #dbName + '].['' + TABLE_SCHEMA + ''].['' + TABLE_NAME + '']'''';''
FROM [' + #dbName + '].INFORMATION_SCHEMA.Views '
EXEC sp_executesql #q , #p ,#sql out
EXEC sp_executesql #sql
END
GO