Showing posts with label Dynamic Stored Procedures in SQL Server. Show all posts
Showing posts with label Dynamic Stored Procedures in SQL Server. Show all posts

Tuesday, 7 February 2012

Dynamic SQL Server stored procedure execution form in SSMS

 

Problem
The purpose for most stored procedures is for execution within applications, but there are some stored procedures that may be used for administrative purposes and only get executed ad hoc.   In addition, during testing you run stored procedures interactively to make sure things are working correctly.  You have the ability to run any stored procedure directly from a query window and include the necessary parameters, but is there any easier way to know what parameters a stored procedure requires and to pass the parameters directly to a stored procedure?

Solution
In SQL Server Management Studio you have the ability to execute a stored procedure directly from the object browser tree.  Just browse to the desired stored procedure and right click and select "Execute Stored Procedure..." as shown below.


When you select "Execute Stored Procedure..." a window such as the following will pop up that will give you the list of parameters to use for the stored procedure.

Enter the value you want to use for the parameter and select "OK" to run the stored procedure.

The stored procedure will execute based on the parameters you pass as well as create sample code such as the following that is used for the execution of the stored procedure.

That's all there is to it.  This is a pretty simple tip, but could save you a lot of time if you need to run a stored procedure and don't want to mess with having to type the commands or if you don't remember the exact parameters that the stored procedure needs.
The only downside to this is that it only works for user defined stored procedures.  System stored procedures do not give you the option to use the "Execute Stored Procedure...".
 Next Steps
  • Next time you need to run a stored procedure use this technique as a faster way to execute the code

Reff ..to Posted by ==By:

 

Simple script to backup all SQL Server databases

ProblemSometimes things that seem complicated are much easier then you think and this is the power of using T-SQL to take care of repetitive tasks.  One of these tasks may be the need to backup all databases on your server.   This is not a big deal if you have a handful of databases, but I have seen several servers where there are 100+ databases on the same instance of SQL Server.  You could use Enterprise Manager to backup the databases or even use Maintenance Plans, but using T-SQL is a much simpler and faster approach.
SolutionWith the use of T-SQL you can generate your backup commands and with the use of cursors you can cursor through all of your databases to back them up one by one.  This is a very straight forward process and you only need a handful of commands to do this. 
Here is the script that will allow you to backup each database within your instance of SQL Server.  You will need to change the @path to the appropriate backup directory and each backup file will take on the name of "DBnameYYYDDMM.BAK".
DECLARE @name VARCHAR(50) -- database name  DECLARE @path VARCHAR(256) -- path for backup files  DECLARE @fileName VARCHAR(256) -- filename for backup  DECLARE @fileDate VARCHAR(20) -- used for file name
SET @path = 'C:\Backup\' 
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
DECLARE db_cursor CURSOR FOR 
SELECT 
name FROM master.dbo.sysdatabases WHERE name NOT IN ('master','model','msdb','tempdb') 
OPEN db_cursor   FETCH NEXT FROM db_cursor INTO @name  
WHILE @@FETCH_STATUS = 0   BEGIN  
       SET 
@fileName = @path + @name + '_' + @fileDate + '.BAK' 
       
BACKUP DATABASE @name TO DISK = @fileName 

       
FETCH NEXT FROM db_cursor INTO @name   END  

CLOSE 
db_cursor   DEALLOCATE db_cursor
In this script we are bypassing the system databases, but these could easily be included as well.  You could also change this into a stored procedure and pass in a database name or if left NULL it backups all databases.  Any way you choose to use it, this script gives you the starting point to simply backup all of your databases.

Wednesday, 25 January 2012

Dynamic Stored Procedures in SQL Server

Dynamic SQL allows stored procedures to “write” or dynamically generate their SQL statements. The most common use case for dynamic SQL is stored procedures with optional parameters in the WHERE clause. These are typically called from reports or screens that have multiple, optional search criteria. This article describes how to write these types of stored procedures so they execute well and resist SQL injection attacks.
A simple example of a stored procedure with dynamic SQL is:

use AdventureWorks
GO
IF  EXISTS (SELECT * FROM sys.objects 
   WHERE object_id = OBJECT_ID(N'[Sales].[GetSalesOrders]') 
   AND type in (N'P', N'PC'))
DROP PROCEDURE [Sales].[GetSalesOrders]
GO

CREATE PROCEDURE [Sales].[GetSalesOrders] (
 @CustomerID INT = NULL,
 @ContactID INT = NULL,
 @debug bit = 0 )
AS
SET NOCOUNT ON; 

DECLARE @SQL NVARCHAR(4000);
DECLARE @ParameterDefinition NVARCHAR(4000);

SELECT @ParameterDefinition = '
 @CustomerParameter INT,
 @ContactParameter INT
';

SELECT @SQL = N'
SELECT [SalesOrderID], [OrderDate], [Status], 
 [CustomerID], [ContactID]
FROM [Sales].[SalesOrderHeader]
WHERE 1 = 1
';

IF @CustomerID IS NOT NULL
 SELECT @SQL = @SQL + N'
 AND CustomerID = @CustomerParameter ';
 
IF @ContactID IS NOT NULL
 SELECT @SQL = @SQL + N'
 AND ContactID = @ContactParameter ';
 
IF @debug = 1
 PRINT @SQL
 
EXEC sp_executeSQL 
 @SQL,
 @ParameterDefinition,
 @CustomerParameter = @CustomerID,
 @ContactParameter = @ContactID; 
GO

EXEC [Sales].[GetSalesOrders] @debug = 1, @CustomerID = 11724

This example uses the sp_executeSQL system stored procedure to execute the SQL.  This provides a fast, safe way to execute dynamic SQL.  It is also possible to use the EXECUTE statement to execute arbitrary strings that contain SQL statements.  I strongly encourage you to avoid this approach.  It may not perform as well and may leave you open to SQL injection attacks.

sp_executeSQL needs two Unicode strings and the parameter values passed to it.  The first Unicode string is the actual SQL statement.  We build this up based on the optional parameters passed into the stored procedure.  We only add the predicates to the WHERE clause that actually have values.  This is the part that handles the optional parameters.  The predicates we add use parameters rather than actual values at this point.  These will be parameterized SQL statements.

Also notice that this stored procedure uses a WHERE 1 = 1 to start the WHERE clause.  It’s a hack to shorten the stored procedure and saves writing code to determine if each predicate is the first predicate added.  It doesn’t affect the query plan of the generated SQL statement.
The second string holds every possible parameter that may appear in the dynamic SQL statement.  It defines the parameter and the data type.  This should hold every possible parameter regardless of whether they are actually used.

The sp_executeSQL statement is passed the generated SQL statement, the list of possible parameters and a mapping of those parameters to actual values.  This maps every parameter whether it was passed into the stored procedure or not.  The mapping is done by name rather than by order.  It ignores the parameters that aren’t found in the actual generated SQL statement.

Performance and Security

This stored procedure is generating parameterized SQL.  This makes it easier for SQL Server to reuse the query plan.
Due to the way we are passing and using parameters it is extremely difficult to attack this stored procedure using SQL injection.  All parameters are type checked as they are passed in.

Other Best Practices

I like to use different names for the parameters inside the generated SQL.  This helps me know exactly where each parameter is coming from.
I often use a debug parameter like you see here.  Tracking down issues with this type of stored procedure can be challenging and this makes it easier.  It has a negligible performance impact.
It’s best not to write code that accepts table and column names as parameters.  That is an easy approach for SQL injection to attack.  If that code must be written, pay careful attention to sanitizing those parameters before using them.