Take value from exec sp_executesql in stored procedure - c#

declare #nopqty decimal(10,2)
declare #ntotamt decimal(10,2)
declare #npartno nvarchar(20)
SET #Orgcd =101
SET #npartno = "A 0001 150"
declare #qry nvarchar(4000)
SET #qry = 'SELECT #nopqty = oqty' + convert(varchar(3), #norgcd) +
', #ntotamt = ocost' + convert(varchar(3), #norgcd) +
' FROM stock WHERE part = #npartno'
exec sp_executesql #qry
Error
Must declare the scalar variable
Then I used
exec sp_executesql #qry, N'#nopqty decimal(10,2),#ntotamt decimal(10,2),#npartno nvarchar(20)',#nopqty=#nopqty,#ntotamt=#ntotamt,#npartno=#npartno
but when print #nopqty, #ntotamt it is null
How can I take out #nopqty, #ntotamt from these #qry?
I need these value for some calculation

Specify the parameter as output. For example:
declare #name varchar(10)
exec sp_executesql
N'select top 1 #name = name from sys.tables',
N'#name varchar(10) output',
#name = #name output
print #name

Related

SqlCommand Parameters.AddWithValue return # instead of variable [duplicate]

I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END

PROCEDURE Return always 0 for string statement

I have a procedure that can be changed dynamically by user for multi column and I write it in SQL when I run it. Everything is OK in SQL and Server Explorer in Visual Studio but when I want use it in C# and call it, it just return 0 always.
Can anybody help me?!
CREATE PROCEDURE [dbo].[PDaynamicActualBy2Column]
#Colname1 nvarchar(100),
#VarCol1 nvarchar(100),
#Colname2 nvarchar(100),
#VarCol2 nvarchar(100),
#VarWeekNum nvarchar(100)
as
DECLARE #temp nvarchar(1500)
set #temp='SELECT SUM([dbo].[WeekActualTemp].[ACTUAL]) from [dbo].[MAINTB] join [dbo].[WeekActualTemp] on [dbo].[MAINTB].[UQ]=[dbo].[WeekActualTemp].[UQ]
where [dbo].[WeekActualTemp].[WeekNO]='+#VarWeekNum+' And [dbo].[MAINTB].'+#Colname1+' = '''+#VarCol1+''' And [dbo].[MAINTB].'+#Colname2+' = '''+#VarCol2+''''
exec (#temp)
This does not address the problem in the C#, however, it does address the huge injection issue you have in your code. Like mentioned, don't inject your parameters and properly quote your dynamic object names. This results in something like the below:
CREATE PROC dbo.PDaynamicActualBy2Column #Colname1 sysname, #VarCol1 nvarchar(100), #Colname2 sysname, #VarCol2 nvarchar(100), #VarWeekNum int AS --Assumed #VarWeekNum is an int, as why else is it called "num"?
BEGIN
DECLARE #SQL nvarchar(MAX),
#CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SET #SQL = N'SELECT SUM(WAT.Actual) AS ActualSum' + #CRLF +
N'FROM dbo.MAINTB MTB' + #CRLF +
N' JOIN dbo.WeekActualTemp WAT ON MTB.UQ = WAT.UQ' + #CRLF +
N'WHERE WAT.WeekNO = #VarWeekNum' + #CRLF +
N' AND MTD.' + QUOTENAME(#Colname1) + N' = #VarCol1' + #CRLF +
N' AND MTD.' + QUOTENAME(#Colname2) + N' = #VarCol2;';
--PRINT #SQL; Your Best Friend
EXEC sp_executesql #SQL, N'#VarCol1 nvarchar(100),#VarCol2 nvarchar(100),#VarWeekNum int', #VarCol1, #VarCol2, #VarWeekNum;
END;
GO
Because you're only returning a single scalar value, you could also use an OUTPUT parameter as well, instead of a SELECT to the display the value. This would look like the below:
CREATE PROC dbo.PDaynamicActualBy2Column #Colname1 sysname, #VarCol1 nvarchar(100), #Colname2 sysname, #VarCol2 nvarchar(100), #VarWeekNum int, #ActualSum int OUTPUT AS --Assumes Actual is an int in your table. Use an appropriate data type
BEGIN
DECLARE #SQL nvarchar(MAX),
#CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SET #SQL = N'SELECT #ActualSum = SUM(WAT.Actual)' + #CRLF +
N'FROM dbo.MAINTB MTB' + #CRLF +
N' JOIN dbo.WeekActualTemp WAT ON MTB.UQ = WAT.UQ' + #CRLF +
N'WHERE WAT.WeekNO = #VarWeekNum' + #CRLF +
N' AND MTD.' + QUOTENAME(#Colname1) + N' = #VarCol1' + #CRLF +
N' AND MTD.' + QUOTENAME(#Colname2) + N' = #VarCol2;';
--PRINT #SQL; Your Best Friend
EXEC sp_executesql #SQL, N'#VarCol1 nvarchar(100),#VarCol2 nvarchar(100),#VarWeekNum int, #ActualSum int OUTPUT', #VarCol1, #VarCol2, #VarWeekNum, #ActualSum OUTPUT; --Again, assumes Actual is an int.
END;
GO
Notice, as mentioned in the comments, I get rid of the 3+ part naming for your columns, and alias your tables instead. I then use those aliases to reference to correct object. I've also put "Your best Friend" in the code, should you need to debug it.
Note: As mentioned in a different answer, zero is likely because the SP is returning 0 to mean success. This is a documented and intentional feature of Stored Procedures:
Unless documented otherwise, all system stored procedures return a value of 0. This indicates success and a nonzero value indicates failure.
As the SP above is likely successful, the RETURN value is 0; to denote success. You shouldn't be looking at the RETURN value, but the dataset, or in the latter example the OUTPUT parameter's value. I am sure there are questions on SO for how to use an OUTPUT parameter in linq.
Zero in return value of your stored procedure means it executed successfully.
You should return a value by "RETURN" statement or "SELECT" statement for table in return.
In LINQ you cannot call an SP that have a meta output that is dynamic, you have to write your SP with "select" output and make a model and then go to SP and edit it again.
Alter PROCEDURE [dbo].[PDaynamicActualBy2Column]
#Colname1 nvarchar(100),
#VarCol1 nvarchar(100),
#Colname2 nvarchar(100),
#VarCol2 nvarchar(100),
#VarWeekNum nvarchar(100)
as
DECLARE #temp nvarchar(1500)
set #temp='SELECT SUM([dbo].[WeekActualTemp].[ACTUAL]) from [dbo].[MAINTB] join [dbo].[WeekActualTemp] on [dbo].[MAINTB].[UQ]=[dbo].[WeekActualTemp].[UQ]
where [dbo].[WeekActualTemp].[WeekNO]='+#VarWeekNum+' And [dbo].[MAINTB].'+#Colname1+' = '''+#VarCol1+''' And [dbo].[MAINTB].'+#Colname2+' = '''+#VarCol2+''''
-- exec (#temp)
SELECT top 0
SUM([dbo].[WeekActualTemp].[ACTUAL]) as sum
from [dbo].[MAINTB] join [dbo].[WeekActualTemp] on [dbo].[MAINTB].[UQ]=[dbo].[WeekActualTemp].[UQ]
then import SP in your LINQ then comment "select" and uncomment "exec" .

Return value from one stored procedure to another

I want to use the return value from one stored procedure to another stored procedure. I was searching on the internet and try several solutions, but all of them are not working, I don't know what the mistake I make.
The stored procedure that I want to use its return value is:
CREATE PROCEDURE dbo.pro_ForeignKeyCheck
(#tableName VARCHAR(100),
#columnName VARCHAR(100),
#idValue INT)
AS BEGIN
SET NOCOUNT ON
DECLARE fksCursor CURSOR FAST_FORWARD FOR
SELECT
tc.table_name, ccu.column_name
FROM
information_schema.table_constraints tc
JOIN
information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name
JOIN
information_schema.referential_constraints rc ON tc.constraint_name = rc.constraint_name
JOIN
information_schema.table_constraints tc2 ON rc.unique_constraint_name = tc2.constraint_name
JOIN
information_schema.constraint_column_usage ccu2 ON tc2.constraint_name = ccu2.constraint_name
WHERE
tc.constraint_type = 'Foreign Key'
AND tc2.table_name = #tableName
AND ccu2.column_name = #columnName
ORDER BY
tc.table_name
DECLARE #fkTableName VARCHAR(100),
#fkColumnName VARCHAR(100),
#fkFound BIT,
#params NVARCHAR(100),
#sql NVARCHAR(500)
OPEN fksCursor
FETCH NEXT FROM fksCursor INTO #fkTableName, #fkColumnName
SET #fkFound = 0
SET #params = N'#fkFound BIT OUTPUT'
WHILE ##fetch_status = 0 AND COALESCE(#fkFound, 0) <> 1
BEGIN
SELECT #sql = 'set #fkFound = (select top 1 1 from [' + #fkTableName + '] where [' + #fkColumnName + '] = ' + cast(#idValue as varchar(10)) + ')'
PRINT #sql
EXEC sp_executesql #sql, #params, #fkFound OUTPUT
FETCH NEXT FROM fksCursor INTO #fkTableName, #fkColumnName
END
CLOSE fksCursor
DEALLOCATE fksCursor
SELECT COALESCE(#fkFound, 0)
RETURN 0
END
and this use to check if the primary key value used in all child tables, we call it like this
EXECUTE pro_ForeignKeyCheck 'tablename','columnName', 1
or
EXECUTE pro_ForeignKeyCheck #tablename = 'tablename', #columnName = 'columnName', #idValue = 1
and it will work, but I cannot use the return value in other stored procedure
CREATE PROCEDURE [dbo].[pro_Delete_acount]
#UserID int,
#Action NVARCHAR(10)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #count int , #ErrNo int , #ErrMsg varchar(2000), #exit int
set #exit=0
if #Action ='ADMIN'
begin
/*---------Call Store Procedure pro_ForeignKeyCheck to check if there is value are exit in child table*/
--EXEC #exit = pro_ForeignKeyCheck1 #tablename='tb_M_admin',#columnName='admin_id',#idValue= #UserID
--select #exit
--EXEC #exit = pro_ForeignKeyCheck #tablename='tb_M_admin',#columnName='admin_id',#idValue= 1
EXEC #exit = pro_ForeignKeyCheck 'tb_M_admin','admin_id', 0
--select #exit
select -2[Ret_Status],#exit[ErrNo],0[ErrMsg] -- test
end
end
Could anyone help me with that?
Thanks all
Add
#Status int OUTPUT
in the pro_ForeignKeyCheck so it starts with
CREATE PROCEDURE dbo.pro_ForeignKeyCheck1
#tableName VARCHAR(100),
#columnName VARCHAR(100),
#idValue int,
#Status int OUTPUT
and at the end of it did as follow
--select coalesce(#fkFound,0)
select #Status = coalesce(#fkFound,0)
--return 0
stop the last to line and add new one
In the other stored procedure, call it as follows
EXEC pro_ForeignKeyCheck1 'tb_M_admin','admin_id', 0 ,#exit output
select #exit
and now the return value will be used.
Thanks to all
EXEC #exit = pro_ForeignKeyCheck 'tb_M_admin','admin_id', 0
---
select coalesce(#fkFound,0)
return 0 --< this will be assigned to #exit
replace this code with
return IsNull(#fkFound, 0)
You may leave select for other purposes but it cannot affect RETURN value. So you may remove it either.
This is oversimplified example of call of one SP from another. I hope it will give you some ideas.
create procedure dbo.first_proc
#bd datetime,
#d int output
as
select #d= DATEDIFF(day,#bd,getdate())
go
create procedure dbo.sec_proc
#birthday datetime
as
declare #days int
exec dbo.first_proc #birthday, #days output
select 'you live '+cast(#days as varchar) + ' days' result
go
exec dbo.sec_proc '1959-09-17'

Need to create a new table from existing table

I want to create a new table with existing table, where the table names should to pass from input parameters.
I am trying the following code.
DECLARE #oldTableName nvarchar(50)
DECLARE #newStagingTableName nvarchar(50)
SET #oldTableName='OldTableName'
SET #newStagingTableName ='NewTableName';
SELECT * INTO #newStagingTableName FROM #oldTableName WHERE 1 = 0;
The SQL server is giving error while parsing this query.
Could you please try below dynamic SQL query?
DECLARE #oldTableName nvarchar(50)
DECLARE #newStagingTableName nvarchar(50)
SET #oldTableName='OldTableName'
SET #newStagingTableName ='NewTableName'
DECLARE #sqlquery nvarchar(100) = 'SELECT * INTO ' + #newStagingTableName + ' FROM ' + #oldTableName
exec(#sqlquery)
On the line
SELECT * INTO #newStagingTableNameFROM #oldTableName WHERE 1 = 0;
you do not have a space between #newStagingTableName and FROM
also check does the table NewTableName exist ? and if so you cannot just access it directly via a parameter - you would need to use dynamic SQL - perhaps this can help
Try with this
DECLARE #oldTableName NVARCHAR(50)
DECLARE #newStagingTableName NVARCHAR(50),
#sql NVARCHAR(100)=''
SET #oldTableName=''
SET #newStagingTableName ='';
SET #sql='select * INTO ' + #newStagingTableName
+ ' FROM ' + #oldTableName + ' WHERE 1 = 0;'
EXEC sp_executesql
#sql
this should work . . .
DECLARE #oldTableName nvarchar(50)
DECLARE #newStagingTableName nvarchar(50)
declare #sql nvarchar(max);
SET #oldTableName='oldTableName'
SET #newStagingTableName ='newStagingTableName ';
SET #sql='SELECT * INTO ' + #newStagingTableName + ' FROM ' + #oldTableName + ' WHERE 1 = 0;'
exec sp_executesql #sql
EDIT: Sorry I didnt see that other guys answered it

SQL execute string issue with National language character?

i have a simple sp in sql as bellow :
alter proc sptest(#val nvarchar(30))
as
select COUNT(*) from AAtable
where name = #val
as i call this sp with #val = 'مریم', it works well and returns value.
but when i change it like this :
alter proc sptest(#val nvarchar(30))
as
declare #q nvarchar(max)
set #q = 'select COUNT(*) from AAtable where name = ' + #val
Execute(#q)
and call it with the same #val, it converts #val value to "?" and returns error. i should say that #val comes from a string parameter in c#. as i know .net convert string to nvarchar parameter form sql. anyway i can not add N before #val.
and also i HAVE to make a string query and execute it so i can not change it to the first code too.
if i do this : set #q = 'select COUNT(*) from AAtable where name = N''' + #val + '''' it does not work too.
why execute string makes my nvarchar parameter to "?" !?
Add the N in front of your text, so it is an NVARCHAR literal, not a VARCHAR, like this: N'My Text'
Try marking the first string of your concatenation operation as explicit Unicode:
set #q = N'select COUNT(*) from AAtable where name = ' + #val
This should keep your #val in Unicode as well.
ALTER proc sptest(#val nvarchar(30))
AS
DECLARE #retval INT
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
SET #SQLString =
N'select #retvalOUT = COUNT(*) from AAtable where name = #Name';
SET #ParmDefinition = N'#Name varchar(30), retvalOUT int OUTPUT';
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#Name = #val,
#retvalOUT=#retval OUTPUT;
SELECT #retval;

Categories

Resources