EXEC sp_executesql will work with Integers but not VarChars - sql

I'm using EXEC sp_executesql for a dynamic query in SQL Server 2017.
I've tried various testing scenarios, and I can get results in my query (for other parameters) as long as the values passed in are Integers. So, that means, Location and Department testing works. However, I can't figure out if there's something I need to do differently for when I'm sending a NVARCHAR or DateTime.
Here's my stored procedure, with the NVARCHAR param. Do you see anything I'm doing wrong?
(
#tktitle NVARCHAR(200)
)
AS
BEGIN
Declare #SQL NVARCHAR(MAX)
Set #SQL = 'SELECT timekeep.tkinit, timekeep.tkfirst, timekeep.tklast,
timekeep.tkemdate, timekeep.tktitle, timekeep.tkloc, timekeep.tkdept
FROM abc.xyz'
IF #tktitle IS NOT NULL
Select #SQL = #SQL + 'AND ([tktitle] = #tktitle)'
EXEC sp_executesql #SQL, N'#tktitle varchar', #tktitle
END

I can identify at least three issues:
You need to specify a length for varchar when passing it as a parameter.
You also need a space before the AND and the AND should be a WHERE.
You need to assign the parameter in the execute call.
So:
IF #tktitle IS NOT NULL
Select #SQL = #SQL + ' WHERE ([tktitle] = #tktitle)';
-------------------------^ separator
EXEC sp_executesql #SQL, N'#tktitle varchar(200)', #tktitle=#tktitle;

Related

EXEC sp_executesql #sql limitation

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:

Get error in string query

I'm a beginner to SQL Server
I wrote this query:
DECLARE #sql nvarchar(1000) = 'UPDATE Work
SET [Name] = Programmer, [ImageAddress] = pic.jpg
WHERE Id = 2'
SELECT #sql
EXEC Sp_executesql #sql
but I get this error
Invalid column name 'Programmer'.
Why do I get this error?
Thank you for your help
You are dealing with SQL in strings. Quoting the strings becomes a challenge. You need for Programmer to be in single quotes when the query is executed. To get this, you need double single quotes in the string:
DECLARE #sql nvarchar(1000)='
UPDATE Work
SET [Name] = ''Programmer'', [ImageAddress] = ''pic.jpg'' WHERE Id=2'
select #sql
EXEC Sp_executesql #sql;
Because you are wise enough to use sp_executesql, you should learn about parameters. You can write the query as:
DECLARE #sql nvarchar(1000)='
UPDATE Work
SET [Name] = #Programmer, [ImageAddress] = #imageaddress WHERE Id=2'
select #sql
EXEC Sp_executesql #sql, N'#programmer nvarchar(255), #imageaddress nvarchar(255)',
#programmer = N'Programmer', #imageaddress = N'pic.jpg';
This has several advantages besides the quoting. It is safer in terms of SQL injection and it allows SQL Server to cache the execution plans if the query is called more than once.
try this:
You need to use '' (Double Quotes for string) Inside Dynamic SQL
DECLARE #sql nvarchar(1000)='
UPDATE Work
SET [Name] = ''Programmer'',[ImageAddress] =''pic.jpg'' WHERE Id=2'
select #sql
EXEC Sp_executesql #sql

Execute sp_executesql, Table Variabe not Declared

I am Using SQL server 2012 and i want to select random columns from my table by applying where condition in this query:
EXECUTE sp_executesql
N'SELECT *
FROM #table
WHERE #Col = #Value',
N'#Value nvarchar(44),#table nvarchar(55),#Col nvarchar(30)',
#Value = 'Cus_1',#Col='CustId',#table='SaleOrder';
But when I execute it, it shows error
Must declare the table variable "#table"
I also tried it to declare by this: #table table(Id nvarchar(30)), but thin it shows again an error on table type...
Please help
This is what you are trying to run:
EXECUTE sp_executesql
N'SELECT * FROM #table WHERE #Col = #Value',
N'#Value nvarchar(44), #table nvarchar(55), #Col nvarchar(30)',
#Value = 'Cus_1', #Col='CustId', #table='SaleOrder';
Alas. You cannot substitute in a table name or column name using parameter substitution. So, SQL Server is looking for a table variable called #table. You can fix this by putting the values directly into the string:
declare #Col = 'CustId', #table = 'SaleOrder';
declare #sql nvarchar(max) = N'SELECT * FROM ' + #table + ' WHERE ' + #Col + ' = #Value';
EXECUTE sp_executesql #sql,
N'#Value nvarchar(44)',
#Value = 'Cus_1';
Unfortunately, I cannot find a good reference in the documentation that explains what is happening. When a statement is compiled, it is allowed to have parameters. However, the parameters are for values in the statement, not for column, table, database, or UDF names or for keywords. The statement itself is compiled, with place holders for the parameters, and in order to be compiled, the SQL engine needs to resolve all object names.

Using variable value in string when executing EXEC in SQL

I want to use a variable value in exec where i don't need to create the query itself.
I will have a query stored in a field in my database and i just want to execute that using the parameters in that stored procedure. For Example below i declared two variables #ValueVariable is the parameter of stored procedure and what i declared #QueryString is the one i will read from data base and i want to execute that using the value of #ValueVariable.
DECLARE #ValueVariable int=0
#QueryString VARCHAR(MAX)=
'SELECT UserName FROM TableUser WHERE UserId=#ValueVariable'
EXEC(#QueryString)
When i try to execute that i get an error Incorrect syntax near 'SELECT UserName FROM TableUser WHERE UserId=#ValueVariable'
I am aware that i can do it by
#QueryString VARCHAR(MAX)=
'SELECT UserName FROM TableUser WHERE UserId='+#ValueVariable
But i want to use it as stated above. Not making a query in my procedure but using variable value as in string retrieved from DB.
So is there any way i could be able to execute that using the value from the variable in current environment.
You can use sp_executesql.
DECLARE
#IntVariable int,
#SQLString nvarchar(500),
#ParmDefinition nvarchar(500)
SELECT
#IntVariable = 0,
#SQLString = N'SELECT UserName FROM TableUser WHERE UserId=#ValueVariable',
#ParmDefinition = N'#ValueVariable INT'
SP_EXECUTESQL
#SQLString,
#ParmDefinition,
#ValueVariable = #IntVariable;
In essence, it creates a one time stored procedure. The #paramDefinition variable is the parameter signature you'd normally see in a stored procedure, the sql server caches the execution plan, etc, etc.

How to set morethan max size charecters in NVARCHAR(MAX),sql Server2005

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)