Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase «««1234

How to Build Dynamic Stored Procedures Expand / Collapse
Author
Message
Posted Monday, December 18, 2006 1:23 PM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Thursday, July 17, 2014 1:37 PM
Points: 1,612, Visits: 1,536

>> A complex statement is difficult to read when it is pieced together with a bunch of CHAR, CAST, and CONVERT fuctions.

I disagree. I think it is easier to read considering I don't have to go to another part of the procedure and find the Replace statements to figure out what someone is trying to do with a particular portion of the dynamic statement.

Of course, the best solution to the nvarchar 4000 character limit is to use nvarchar(max) in SQL Server 2005.





My blog: SQL Soldier
Twitter: @SQLSoldier
My book: Pro SQL Server 2008 Mirroring
Microsoft Certified Master: SQL Server 2008
Principal DBA: Outerwall, Inc.
Also available for consulting: SQL DBA Master
Post #331387
Posted Monday, December 18, 2006 6:34 PM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Today @ 9:15 AM
Points: 1,502, Visits: 2,667

The "best" solution is not to use dynamic sql unless there is absolutely no other way to accomplish the desired result.

Dynamic sql is a total pain to maintain. I've slogged through other people's dynamic code and many times found a better way.

If you must write dynamic sql, you should embed a sample of the resulting sql statement in the sp, to help illustrate what's going on. A very simple example of that would be:

-- use the next invoice # as the seed, might look like:
-- ALTER TABLE tblFM_MPI ADD InvoiceNumber int IDENTITY (45969, 1)
SET @sql = N'ALTER TABLE tblFM_MPI DROP COLUMN InvoiceNumber'
EXEC ( @sql )
SET @sql = N'ALTER TABLE tblFM_MPI ADD InvoiceNumber int IDENTITY (' + CAST(@NextInv AS varchar(6)) + ', 1)'
EXEC  ( @sql )

 

Post #331453
Posted Monday, December 18, 2006 7:37 PM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Thursday, July 17, 2014 1:37 PM
Points: 1,612, Visits: 1,536

On a related note, we have a project in development for our internal account managers and tech support team to be able to run any select query they want against our databases to help them resolve issues. The devloper asked me how she could go about making sure they didn't inadvertantly perform some query other than a select. My reply was to create a user account that had all privelages denied except for select and execute the procedure as that user account. Bear in mind that the AM's and tech support will be using a web app that is using an account whose only rights is to execute stored procedures.

This is the real code that was finally used, but is the initial test code I sent to the developer for testing how it would work. Bear in mind that this is SQL 2005 code.

Use master

-- Create server login for test

Create Login DBDataReaderOnly With Password = 'PeasPorridgeCold'

Use DemoDatabase

-- Create database user for login

Create User DBDataReader For Login DBDataReaderOnly With Default_Schema = dbo

-- Create databse role for easy assignment of permissions

Create Role db_DataReaderOnly

-- Grant select rights

Grant Select To db_DataReaderOnly

-- Deny all other permissions

Deny Execute, Insert, Update, Delete, References, Alter, Take Ownership, View Definition To db_DataReaderOnly

-- Assign user to the database role

Exec sp_addrolemember 'db_DataReaderOnly', 'DBDataReader'

Go

-- Create a test procedure

Create Procedure dbo.USP_DynamicDataTest

@SQL nvarchar(max)

With Execute As 'DBDataReader'

As

Exec sp_executesql @SQL

Go

-- Test new account, run each command individually

Exec dbo.USP_DynamicDataTest @SQL = 'Select * From TestTable with(nolock)'

Exec dbo.USP_DynamicDataTest @SQL = 'Delete Top (1) From TestTable'

Exec dbo.USP_DynamicDataTest @SQL = 'Drop Table TestTable'

 





My blog: SQL Soldier
Twitter: @SQLSoldier
My book: Pro SQL Server 2008 Mirroring
Microsoft Certified Master: SQL Server 2008
Principal DBA: Outerwall, Inc.
Also available for consulting: SQL DBA Master
Post #331455
Posted Tuesday, January 8, 2008 11:38 AM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Monday, November 16, 2009 8:50 AM
Points: 3, Visits: 10
Does anyone actually test this code or is most of this stuff just rumors?
According to most of the information I should be able to create multiple variables...

DECLARE @SELECT varchar(100)
DECLARE @FROM varchar(100)
DECLARE @DynamicSQL1 varchar(8000)
DECLARE @DynamicSQL2 varchar(8000)
DECLARE @DynamicSQL3 varchar(8000)

SET @SELECT = 'SELECT '
SET @FROM = 'FROM DATA_SOURCE'

EXEC (@SELECT + @DynamicSQL1 + @DynamicSQL2 + @DynamicSQL3 + @FROM)


The exec statement only accesses the first 8000 characters and then shuts down.

What am I missing/
Post #440204
Posted Tuesday, January 8, 2008 1:10 PM
SSCrazy

SSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazySSCrazy

Group: General Forum Members
Last Login: Friday, July 18, 2014 12:13 PM
Points: 2,837, Visits: 1,138
Seems to work for me in both SQL 2000 and SQL 2005. This code creates a 16,000+ character command that returns 16 996-char fields and one 3-char field as results.

DECLARE @v1 VARCHAR(8000), @v2 VARCHAR(8000)
SET @v1 = '''' + LEFT(REPLICATE('1234567890', 100), 996) + ''', '

SET @v2 = REPLICATE(@v1, 8)
SET @v1 = @v2

EXEC ('SELECT ' + @v1 + @v2 + '''xyz''')

Maybe there's a syntax error in your command.



Post #440263
Posted Tuesday, January 8, 2008 3:00 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Monday, November 16, 2009 8:50 AM
Points: 3, Visits: 10
Thank you for the quick reply and yes, I tested your code and it works fine on my system so, in theory, I should have a syntax error.

Taking my example below, I mad a change...all the way down, the first exec line fails and the second exec line works. I am at a loss as to why.

DECLARE @SELECT varchar(100)
DECLARE @FROM varchar(100)
DECLARE @DynamicSQL1 varchar(8000)
DECLARE @DynamicSQL2 varchar(8000)
DECLARE @DynamicSQL3 varchar(8000)

SET @SELECT = 'SELECT '
SET @FROM = 'FROM DATA_SOURCE'

EXEC (@SELECT + @DynamicSQL1 + @DynamicSQL2 + @DynamicSQL3 + @FROM)
EXEC (@SELECT +''+ @DynamicSQL1 +''+ @DynamicSQL2 +''+ @DynamicSQL3 +''+ @FROM)
Post #440312
Posted Tuesday, January 8, 2008 3:31 PM
Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Today @ 4:09 PM
Points: 3,121, Visits: 11,395
I made extensive use of stored procedures that created temporary stored procedures for reporting in a data mart application. This reason I did this was because there could be literally hundreds of different variations of the same basic report summarized along different dimensions and levels. The input parameters to the stored procedure specified the grouping/sorting levels that were required, and the stored procedure used that to generate the code.

It was easier to write one fairly complex procedure than it was to create hundreds of almost identical, simpler procedures for the different variations in the reports. The biggest advantage was that if there was a bug, I only had to fix it in one procedure instead of hundreds.







Post #440320
Posted Tuesday, January 8, 2008 4:27 PM
SSC Rookie

SSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC Rookie

Group: General Forum Members
Last Login: Wednesday, July 9, 2014 2:50 PM
Points: 40, Visits: 343
markybse (1/8/2008)


... the first exec line fails and the second exec line works. I am at a loss as to why.

DECLARE @SELECT varchar(100)
DECLARE @FROM varchar(100)
DECLARE @DynamicSQL1 varchar(8000)
DECLARE @DynamicSQL2 varchar(8000)
DECLARE @DynamicSQL3 varchar(8000)

SET @SELECT = 'SELECT '
SET @FROM = 'FROM DATA_SOURCE'

EXEC (@SELECT + @DynamicSQL1 + @DynamicSQL2 + @DynamicSQL3 + @FROM)
EXEC (@SELECT +''+ @DynamicSQL1 +''+ @DynamicSQL2 +''+ @DynamicSQL3 +''+ @FROM)



I'm not sure of the exact problem, but I'd guess it stems from one of two likely sources.
1. The @DynamicSQL# variables need an interceding space in order for their concatenation to result in syntactically correct SQL.
Try:
EXEC (@SELECT + ' ' + @DynamicSQL1 + ' ' + @DynamicSQL2 + ' ' + @DynamicSQL3 + ' ' + @FROM)

2. You are trying to concatenate Null values. The solution would be to recast the @DynamicSQL# as a space if the value is Null.



Post #440341
Posted Wednesday, January 9, 2008 8:16 AM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Monday, November 16, 2009 8:50 AM
Points: 3, Visits: 10
I believe that the second portion, "trying to concactinate NULL values" could be a good start in finding out why it is not working. Thanks again.
Post #440696
« Prev Topic | Next Topic »

Add to briefcase «««1234

Permissions Expand / Collapse