views:

363

answers:

3

I am trying to write a stored procedure that takes a table name as a parameter. Yes I already know this is a security vulnerability, but this is an internal stored proc that doesn't face typical risks of SQL Injection.

What I have so far is something like the following:

CREATE PROCEDURE [dbo].[myprocedure]
    @tableName sysname
AS
DECLARE @cmd nvarchar(4000)
SET @cmd = N' Select blah blah from ' + @tableName
EXEC (@cmd)
GO

The query will work in theory, but my problem is that my query is longer than 4000 characters. Is there another way to use @tableName in a cmd variable longer than 4000 characters (which is nvarchar's max)?

+2  A: 

Extract some of your logic into views or user defined functions.

recursive
+7  A: 

If you use SQL Server >= 2005, try replacing nvarchar(4000) with nvarchar(MAX).

Heinzi
That did not work. I am running SQL Server 2005. The problem is that the MAX is actually 4000.
a432511
@a432511: That's not correct. The maximum size of varchar(MAX) is 2^31.
Michael Petrotta
Hm... I am beginning to think you are right with this suggestion and it may have fixed my main issue, but I also have a syntax problem in my query. Thanks for the help!
a432511
1+ thanks again.
a432511
+1 nvarchar(MAX) is up to 2 Gig or 1073741823 characters.
DancesWithBamboo
+3  A: 
DECLARE @cmd NVARCHAR(MAX);
Remus Rusanu
That did not work. I am running SQL Server 2005. The problem is that the MAX is actually 4000.
a432511
No, MAX is 2^31-1 which is actually 2147483647
CodeByMoonlight
1+ you were correct along with Heinzi, but he responded first. Thanks for your help
a432511