How to use numeric int in exec sp_executesql - sql-server-2008

Is there any way i can use numeric integer in sp_executesql ?
declare #total_test int
declare #test int
set #sql=N'select #test=count (*) from '+#db+'..'+#table
exec sp_executesql #sql
set #total_test +=#test
The problem is that he will not accept any numeric integet,
i cant even set #sql=N'select count (*)...'
Any ideas? Thanks for your help.

You will need to use the OUTPUT clause with your variable. Also on a side note you must use QUOTENAME() function when concatenating object names to your dynamic sql string, protects you against possible sql injection attack.
declare #total_test int;
declare #test int;
SET #total_test = 0;
set #sql=N'select #test=count (*) from '+ QUOTENAME(#db)+'..'+ QUOTENAME(#table)
EXECUTE sp_executesql #sql
,N'#test int OUTPUT'
,#test OUTPUT
set #total_test +=#test

Related

Conversion failed when converting the nvarchar value '2151','1886' to data type int

I have the below query
DEClare #Plan_ID nvarchar(100)
set #Plan_ID=REPLACE('2151,1886',',',''',''')
and
SELECT distinct Plan_Dict_Id from REF_Plan_Dictionary WHERE
CAST(Plan_Dict_Id as int) in (#Plan_ID),
Pls help , Plan_Dict_Id datatype is INT, I want to pass the values to where , but getting error "Conversion failed when converting the varchar value '2151','1886' to data type int."
If this is one of the later versions of SQL Server then you could do something like this...
DECLARE #Plan_ID nvarchar(100)
SET #Plan_ID= '2151,1886'
SELECT DISTINCT Plan_Dict_Id
FROM REF_Plan_Dictionary d
JOIN string_split(#Plan_ID, ',') s ON d.Plan_Dict_Id = s.[value]
If you are using an older version you could put the whole statement in a string and then execute it, however you have a problem in your first line as you are not adding quotes around the string... I've accounted for that below.
DEClare #Plan_ID nvarchar(100) set #Plan_ID=REPLACE('2151,1886',',',''',''')
DECLARE #sql nvarchar(max)
SET #SQL = 'select distinct Plan_Dict_Id from REF_Plan_Dictionary where CAST(Plan_Dict_Id as int) in (''' + #Plan_ID + ''')'
EXEC (#sql)

Want to get selected value

declare #qry as varchar(max)
declare #db as varchar(25)
declare #item as varchar(25)
declare #U_Parentcode as varchar(25)
set #U_Parentcode ='CDM51306520'
set #db ='Marda_Test'
set #qry ='select #item =itemcode from ' + #db + '.[dbo].[OITM] where ItemCode=''' + #U_Parentcode +''''
execute (#qry)
print #item
am getting error like 'Must declare the scalar variable "#item".'
The dynamic sql executes in a different context from the context of your code, so basically there isn't an #item variable declared over there.
You need to use sp_executeSql which contains a mechanism to map your variables to variables within the block. The syntax is a but obtuse, but it's obvious when you get used to it.
declare #qry as nvarchar(max)
declare #db as varchar(25)
declare #outsideItem as varchar(25)
declare #U_Parentcode as varchar(25)
set #U_Parentcode ='CDM51306520'
set #db ='Marda_Test'
set #qry ='select #insideItem =itemcode from ' + #db + '.[dbo].[OITM] where ItemCode=''' + #U_Parentcode +''''
execute sp_executesql #qry, N'#insideItem varchar(25) output', #insideItem = #outsideItem output
print #item
The first parameter is the query, same as with exec().
The second parameter is a declaration of all parameters used in the query, in your case #insideItem.
The third (and any subsequent) parameter is a mapping that says which inside parameter should be mapped to which outside parameter.
The output clause (used both on the variable declaration and on the mapping) is a designator that that parameter is used as an output value of the query.
Your declare statements are not included in #qry content.
In addition, why are you even bothering with execute ?
Why not just use a normal query. Parameterize your connection string so that you connect to the correct database and just run a normal query.

Initializing table name to be used in a stored procedure in SQL Server

I am trying to create a stored procedure to achieve the following in the stored procedure
DECLARE #TBLNAME VARCHAR(128)
SET #TBLNAME = SELECT PAR_VALUE FROM DBO.PARAMETERS WHERE PAR_NAME='SALES_ORDERS_TABLE';
The PAR_VALUE column in the PARAMETERS table contains the name of the table of the Sales Order table.
I now want to use this table name in the stored procedure, and count the number of rows in this table.
DECLARE #SQL NVARCHAR(4000)
# SQL = SELECT COUNT(*) FROM '[#TBLNAME]'
However, when I try to run this, there are multiple errors.
Can you please help me by guiding on how to do this?
I just now tried this code:
CREATE PROCEDURE JCOUNT_SO
AS
DECLARE #TBLNAME NVARCHAR(512)
SELECT #TBLNAME=(SELECT PAR_VALUE FROM DBO.PARAMETERS WHERE PAR_NAME='SALES_ORDERS_TABLE')
DECLARE #SQL NVARCHAR(4000)
SELECT #SQL='SELECT COUNT(*) AS #_OF_RECORDS INTO SO_COUNT
FROM' '+QUOTENAME(#TBLNAME)''
EXEC SP_EXECUTESQL #SQL;
Error Message: Invalid Object Name: 'TEST.DBO.SO_MASTER'
Please help on this code.
Please read defination of sp_executesql for reference. Procedure below returns value as an output parameter from dynamic query rather than inserting into a table. You can manipulate query as per your requirement.
CREATE PROCEDURE JCOUNT_SO
AS
DECLARE #TBLNAME nvarchar(512)
--Obtain table name. Top 1 is used to pick first record rather than last record in case query returns more than one record.
SELECT TOP 1 #TBLNAME = PAR_VALUE FROM DBO.PARAMETERS WHERE PAR_NAME='SALES_ORDERS_TABLE'
DECLARE #SQL NVARCHAR(4000)
DECLARE #Count int
SET #SQL ='SELECT #Count = COUNT(*) FROM ' + #TBLNAME
--Define parameters to be passed i.e. #Count is being passed as output parameter
EXEC SP_EXECUTESQL #SQL, N'#Count int OUTPUT', #Count output
select #Count
end
Notes from MSDN
Query i.e. #SQL can contain parameters having the same form as a variable name and each parameter included in #SQLmust have a corresponding entry in both the #params parameter definition list and the parameter values list
1 point I can say is ... it should be SET #SQL = SELECT ...
and one more thing is you can try converting the result to NVARCHAR.
use SELECT Convert(NVARCHAR(4000),Count(*)) FROM ...

Stored Procedure Dynamic SQL stored result in variable

I have A stored procedure written
DECLARE #AreaID AS INT
DECLARE #DayPrior AS INT
DECLARE #TableName AS VARCHAR(50)
DECLARE #StoreQuery AS NVARCHAR(MAX)
DECLARE #SQL_ExtractDlSql AS NVARCHAR(MAX)
DECLARE #ParameterDefinition AS NVARCHAR(2000)
SET #AreaID = 1
SET #DayPrior = 1
SET #TableName = 'Tbl_Lube'
SET #SQL_ExtractDlSql = 'SELECT Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=#AreaID AND TableName=#TableName'
SET #ParameterDefinition = '#AreaID INT,#DayPrior INT,#TableName VARCHAR(50)'
EXECUTE sp_executesql #SQL_ExtractDlSql,
#ParameterDefinition,
#AreaID,
#DayPrior,
#TableName
PRINT #SQL_ExtractDlSql
I above Stored procedure, I get What I wanted on print, but instead of doing that, I wanted the selected data stores as a variable.
Then what I done is I declared a variable #StoreSql and made some modified into the SQL statement show below:
Variable Declaration:
DECLARE #StoreSql AS NVARCHAR(MAX)
Modified the Code:
SET #SQL_ExtractDlSql = 'SELECT #StoreSql = Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=#AreaID AND TableName=#TableName'
I executed the code, I get error Must declare the scalar variable "#StoreSql".
I have totally no idea how to deal with this.Any one can help.Beside,I am new to sqlserver,new to stored procedures.
Please don't hesitate to point out my any mistake,any..such as logic or etc. I learn from mistake.
Regards
LiangCk
The dynamic SQL string cannot reference variables from the outer scope. You need to declare it as an output parameter
SET #ParameterDefinition = '#AreaID INT,
#DayPrior INT,
#TableName VARCHAR(50),
#StoreSql NVARCHAR(MAX) OUTPUT'
EXECUTE sp_executesql #SQL_ExtractDlSql,
#ParameterDefinition,
#AreaID,
#DayPrior,
#TableName,
#StoreSql OUTPUT

SQL Server use EXEC/sp_executesql or just plain sql in stored procedure?

I have a simple sproc, what is the best way to code it for best query caching/optimization?
I currently have it as follows.
ALTER PROCEDURE dbo.OccupierGet
(
#OccupierID int = 0
)
AS
/* SET NOCOUNT ON */
--Get all details that can be editted.
select TOP 1 ID,AccountNumber,FirstName,LastName,Company,Telephone,Notes,
OccupierTypeID,Address,Address2,City,Country,Telephone2,HomePhone,CellPhone,WorkPhone,Fax,EmailAddress
from dbo.Occupier
where ID = #OccupierID
RETURN
Would it be better to build the sql query as a string and run with sp_executesql and pass the parameter? I'm asking because of query caching and the parameter I'm using.
Thank you!
Tim
See no reason to use dynamic SQL here. When you do need to use dynamic SQL, you should consider sp_executesql higher in preference than EXEC(). There are a variety of reasons, including:
sp_executesql is more likely to reuse query plans (see Dynamic SQL - EXEC(#SQL) versus EXEC SP_EXECUTESQL(#SQL));
it is much easier to pass strongly-typed parameters into sp_executesql (thwarting SQL injection better than concatenating a string); and,
you can also get variables from within the dynamic SQL scope back out to the calling scope, for example:
DECLARE #i INT, #sql NVARCHAR(MAX), #dbname SYSNAME = N'model';
SET #sql = N'SELECT #i = COUNT(*) FROM '
+ #dbname + '.sys.tables;'
EXEC sp_executesql #sql, N'#i INT OUTPUT', #i = #i OUTPUT;
PRINT #i;
That's not a very useful example, but it is a common problem when executing dynamic strings. But more to the point, you should only be considering dynamic SQL when you have to, not as a first resort.