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)?
If you use SQL Server >= 2005, try replacing nvarchar(4000) with nvarchar(MAX).
DECLARE #cmd NVARCHAR(MAX);
Extract some of your logic into views or user defined functions.
Use
DECLARE #cmd VARCHAR(8000)
instead of DECLARE #cmd NVARCHAR(MAX);
NVARCHAR(MAX) ALLOWS ONLY 4000 CHARACTERS.
Related
I want to use the value from variables that is passed into the stored proc. Is that allow?
For example, I want to pass CID=5,SID=4 Into an Update Stored Proc
and it looks like this:
CREATE PROCEDURE Update #CID nvarchar(4),#SID nvarchar(4)
AS
DELETE FROM [User"+#CID+#SID+"]
GO;
In which is like "DELETE FROM [User54]"
But I want to dynamically done given the parameter
Can it be done and how is it done?
Thanks
You must use dynamic SQL. To do it safely, ensure the created object name is properly delimited using the quotename function.
Like this:
CREATE OR ALTER PROCEDURE UpdateSomeTable #CID nvarchar(4), #SID nvarchar(4)
AS
begin
declare #tableName nvarchar(500) = quotename(concat('User',#CID,#SID));
declare #sql nvarchar(max) = concat('DELETE FROM ',#tableName);
--print #sql
exec sp_executesql #sql
end
I am having problem with executing dynamic SQL Server code.
I have an insert into temp table and the number of chars is more than 4000.
I tried to split into two variables and then concatenated them but problem is
EXEC sp_executesql #sql,
N'#DimStartDate int, #DimEndDate bigint',
#DimStartDate, #DimEndDate;
I found on net that EXEC(#sql1+#sql2) is solution but I really need input parameters. How can I solve this?
I have dealt with a similar issue before, like below. Basically you need to separate your main query into pieces, then combine them in the end and use sp_EXECUTESQL to run your dynamic query.
DECLARE #SQL_Part1 varchar(4000);
DECLARE #SQL_Part2 varchar(4000);
DECLARE #SQL_Part3 varchar(4000);
DECLARE #SQL_Part4 varchar(4000);
DECLARE #SQL_Part5 varchar(4000);
DECLARE #SQL_FullQuery nvarchar(MAX);
.. set your queries...
SET #SQL_FullQuery = CAST(#SQL_Part1 + #SQL_Part2 + #SQL_Part3 + #SQL_Part4 + #SQL_Part5 as nvarchar(MAX));
EXEC sp_EXECUTESQL #SQL_FullQuery;
I have had no problem with sp_executesql on strings very long strings. You simply need to declare the query to be long enough:
declare #sql nvarchar(max);
You can have an error inserting into a table if the row length is too long for the table. That would have nothing to do with the dynamic statement. The maximum length of a row is limited in SQL Server -- although you can use long strings and blobs to work around that.
Not sure exactly where the problem is. SQL Server will happily execute more than 4,000 characters, so your SQL must be getting truncated somewhere else. Here is an example where I've manually built up a batch that is more than 4,000 characters total so you can see that all three SELECT statements run and if you copy and paste the middle result you'll see it has the y at the end:
DECLARE #sql nvarchar(max) = N'SELECT 1;'
+ N'SELECT ''' + CONVERT(nvarchar(max), REPLICATE('x', 4096)) + N'y'';';
+ N'SELECT 2;';
EXEC sys.sp_executesql #sql;
Results:
I want to use a database which name is stored in a variable. How do I do this?
I first thought this would work but it doesn't:
exec('use '+#db)
That will not change database context
Suggestions anyone?
Unfortunately I don't know of a direct solution to this one. The nearest working version is:
DECLARE #db nvarchar(MAX)
SET #db = 'use DBname'
Exec sp_executesql #db
but this only changes the context for the length of the procedure call. However, more statements can be included in that call to make use of the context:
DECLARE #sql nvarchar(MAX)
SET #sql = 'use DBName SELECT * FROM Table1'
Exec sp_executesql #sql
If you absolutely have to do this using dynamic SQl, I prefer this:
DECLARE #sql nvarchar(MAX)
declare #databasename varchar (20)
Set #databasename = mydatabase
SET #sql = 'SELECT * FROM ' + #databasename + 'dbo.Table1'
Exec sp_executesql #sql
The reason I prefer it is that you can extend it to use multipe datbases in the same query if need be.
I havea a concern that you don't know the datbase name for each table already without resorting to dynamic means. In other words, why can't you write:
SELECT * FROM mydatabase.dbo.Table1
If you have multiple databases with the same table names, likely you have a design problem.
The use statement is only in scope inside the exec block. Therefore you would have to do everything else in the same exec:
exec('use '+ #db + '
--do other stuff'
)
Presumably you know all the possible database names. One (slightly inelligant) way of doing this would be to use a CASE or multiple IF statements to test the variable and hardcode the USE statement for each case.
I am using
declare #insertsql nvarchar(MAX)
--above #insertsql for sp_executesql takes only nvarchar as input
set #insertsql='--i am giving More than 10000 characters here -----'
EXEC sp_executesql #insertsql, N'#inXMLRequest XML OUTPUT', #inXMLRequest OUTPUT
how to insert morethan 10000 charecters in NVARCHAR(MAX) in sql server2005
can any one help please
Thanks in advance
This has happened to me when I use inline SQL statements instead of stored procs.
If you are hitting that ceiling, you may want to consider moving to stored procs.
The parameter that you use for the command to run in sp_executesql (#insertsql in your case) is NVARCHAR(4000) not NVARCHAR(MAX) so you are limited to a 4000 character dynamic SQL command.
If you are running out of space in the variable, you'll need to do some code re-factoring.
Thanks to All,
i got the answer
Insted of using SP_Executesql directly we Executing nvarchar variable
Above we Are preparing #insertsql nvarchar variable morethan 8000 characters and it is giving to sp_executesql like this
EXEC sp_executesql #insertsql, N'#inXMLRequest XML OUTPUT',#inXMLRequest OUTPUT
insted of above query replaced with below query
Exec ('DeClare #inXMLRequest XML SET #inXMLRequest='------above 8000 characters---')
Finally we will execute that nvarchar string and get out put
sp_executesql will accept an NVARCHAR(MAX) which can be longer than 4000, only it cannot be assigned all at once. It needs to be assigned 4000 characters in a single assignment statement and then appended as shown here:
declare #strSQL nvarchar(max)
--#strSQL + REPLICATE(' ', 5000)+' ''ERROR!'''
--exec sp_executesql #strSQL
SET #strSQL = N'SELECT'+ REPLICATE(' ', 3000)
SET #strSQL = #strSQL + REPLICATE(' ', 3000)+' ''This works'''
exec sp_executesql #strSQL
select LEN (#strSQL)
Trying to update a table on a linked server (SQL 2000/2005) but my server name will not be known ahead of time. I'm trying this:
DECLARE #Sql NVARCHAR(4000)
DECLARE #ParamDef NVARCHAR(4000)
DECLARE #SERVER_NAME VARCHAR(35)
SET #Sql = 'UPDATE
#server_name_param.dba_sandbox.dbo.SomeTable
SET SomeCol=''data'''
SET #ParamDef = N'#server_name_param VARCHAR(35)'
print #Sql
exec sp_executesql #Sql, #ParamDef, #server_name_param=#SERVER_NAME
Which returns this:
UPDATE
#server_name_param.dba_sandbox.dbo.SomeTable
SET SomeCol='data'
Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near '.'.
Any ideas? Is there anyway I view the SQL statement that is being executed after the parameters are bound?
You'll have to do this, it can't be parameterised
....
SET #Sql = 'UPDATE ' + #server_name_param + '.dba_sandbox.dbo.SomeTable SET SomeCol=''data'''
....
Edit: There is another way which I used back in my pure DBA days
EXEC sp_setnetname 'AdhocServer', #SERVER_NAME
UPDATE AdhocServer.dba_sandbox.dbo.SomeTable SET SomeCol 'data'
EXEC sp_setnetname 'AdhocServer', 'MeaninglessValue'
sp_setnetname is there from SQL Server 2000 to 2008
Edit2. Permissions:
Try EXECUTE AS LOGIN = 'login_name' , where login_name is a superuser
I've not really used this (I use "AS USER" for testing), so not sure of the finer points...
Edit 3: for concurrency, consider using sp_getapplock and a stored procedure, or some other concurrency control mechanism.
You cannot do this with parameters directly - you would have to use dynamic SQL, or send the server name as a parameter to an SP that does dynamic SQL:
DECLARE #template NVARCHAR(4000)
DECLARE #Sql NVARCHAR(4000)
DECLARE #SERVER_NAME VARCHAR(35)
SET #template = 'UPDATE {#server_name_param}.dba_sandbox.dbo.SomeTable SET SomeCol=''data'''
SET #sql = REPLACE(#template, '{#server_name_param}', #SERVER_NAME)
print #Sql
exec sp_executesql #Sql -- OR EXEC ( #sql )
I like gbn's trick. I didn't know that one and I'm gonna have to research that some more.
Since I didn't know that trick, I've had to use dynamic sql in similar situations in the past (like what Cade posted). When that happens I would normally query an information schema view to make sure the parameter value is a real database object before building the query. That way I'm sure it's not an injection attempt.