Parameter passing to stored procedures in SQL - c#

I have a SQL procedure that I'm calling from my c# code.
cmd = new SqlCommand("InsertData", con, transaction);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#IP_No", SqlDbType.VarChar, 50);
cmd.Parameters["#IP_No"].Value = data.IP_No;
result = cmd.ExecuteNonQuery().ToString();
This is my procedure:
(
#IP_No varchar(15),
#Indent_No varchar(20)
)
AS
BEGIN
set #Indent_No = (SELECT IndentId from IdTable)
INSERT INTO InsertData(IP_No,Indent_No)
VALUES(#IP_No,#Indent_No)
Update IdTable set IndentId=IndentId+1;
END
Basically, I want my ID to be pulled from a database where I keep incrementing it.
It throws this error:
Procedure or function expects parameter #Indent_No which was not
supplied.
Please Help!

As you use #Indent_No only internally within the stored procedure, you don't need to declare it as an input parameter. You need to declare it within the body of your stored procedure
CREATE PROCEDURE InsertData
(
#IP_No varchar(15)
)
AS
BEGIN
DECLARE #Indent_No varchar(20)
set #Indent_No = (SELECT IndentId from IdTable)
INSERT INTO InsertData(IP_No,Indent_No)
VALUES(#IP_No,#Indent_No)
Update IdTable set IndentId=IndentId+1;
END

Related

Select Scope Identity from Sql

I am executing an Insert query. I want to return the identity element. I am also using this same stored procedure. Inside another stored procedure to return the identity element.
Alter Proc Proc1
#name varchar(10),
#value int
As
Begin
insert into Table1
values (#name, #value)
return SCOPE_IDENTITY()
C# code:
I have a method to call my database every time, so I use that
_database.StoredProcedure = "Proc1";
_database.parameter("name","michael");
_database.parameter("value",10);
int id = Convert.ToInt32(_database.ExecuteScalar());
Here, I get id=0 every time //BUG
SQL other stored procedure:
Alter Proc2
// Some other logic
Execute #id = Proc1 #name, #value // THIS WORKS
Now, If I change Proc1's last line to Select SCOPE_IDENTITY() from RETURN SCOPE_IDENTITY() then C# code works but Proc2 returns 0.
What should I do such that it works in C# code and in Proc2 also.
I thought about an output parameter, but I don't know how would I call it with my this database method in C#.
If you want data out of a procedure the correct thing is to use output parameters. Do NOT use the return_value from your procedures. This value indicates a status of the execution, not data from the procedure.
Here is an example of what this might look like.
Alter Proc Proc1
#name varchar(10),
#value int,
#IdentityValue int OUTPUT
As
Begin
insert into Table1 values (#name,#value)
Select #IdentityValue = SCOPE_IDENTITY()
END
select * from table1
GO
Alter Proc2
(
#name varchar(10)
, #value int
, #IdentityValue int OUTPUT
)
as
//SOme other logic
declare #IdentityValue int
Execute Proc1 #name, #value, #IdentityValue OUTPUT
GO
Also, please notice that you have an insert in Proc1 but you don't specify the columns. This is very bad practice. If your table structure changes your procedure is broken. You should ALWAYS specify the columns in your insert.
Change your procedure body to like below, to change the RETURN statement to SELECT SCOPE_IDENTITY()
Alter Proc Proc1
#name varchar(10),
#value int
As
Begin
insert into Table1 values (#name,#value);
SELECT SCOPE_IDENTITY();
END
In that case, make it a output parameter and set that output parameter to scope_identity
Alter Proc Proc1
#name varchar(10),
#value int,
#ID INT OUTPUT
As
Begin
insert into Table1 values (#name,#value);
SET #ID = SCOPE_IDENTITY();
END
You can call the procedure
cmd.Parameters.Add("#ID", SqlDbType.Int, 0, "ID");
cmd.Parameters["#ID"].Direction = ParameterDirection.Output;
conn.Open();
cmd.ExecuteNonQuery();
int id = (int)cmd.Parameters["#ID"].Value;

output parameter returns null value when I run on ADO. NET in C#

I'm sure this question has already been answered in this forum. I went through most of them and tried all the possible fixes but it did not work in my case. I'm not sure where I'm going wrong.
My stored procedure works fine in SQL Server Management Studio. It is returning the output whenever I run my stored procedure. But the output parameter returns NULL value when I call it from my ADO. NET code. I'm pretty new to this. Any help to resolve this issue is very much appreciated.
Stored Procedure :
CREATE PROCEDURE [dbo].[sp_ZebraGetEmpName]
#EmpId int,
#EmpName varchar(40) out
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT EmployeeName
FROM ZebraPrinter.dbo.EmployeeInfo
WHERE EmpID = #EmpId
RETURN (#EmpName)
END
GO
ADO .NET Code :
public string GetEmpName(int EmpId)
{
string connStr = ConfigurationManager.ConnectionStrings["ZebraPrinterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("sp_ZebraGetEmpName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpId",EmpId);
cmd.Parameters.Add("#EmpName", SqlDbType.VarChar, 40);
cmd.Parameters["#EmpName"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteScalar();
con.Close();
string EmpName = cmd.Parameters["#EmpName"].Value.ToString();
return (EmpName);
}
You didn't assign any values to #EmpName variable in procedure so it will be NULL. Change the select query to assign value to #EmpName
Also you don't need procedure to do this.
SELECT #EmpName=EmployeeName
FROM ZebraPrinter.dbo.EmployeeInfo
WHERE EmpID = #EmpId
You getting the null value in the output parameter because you are not assigning the value to the output parameter.
When you are using a output parameter then you have to set it's value in the stored procedure to use it's value later.
Use:
SET #EmpName = (SELECT TOP 1 EmployeeName
FROM ZebraPrinter.dbo.EmployeeInfo
WHERE EmpID = #EmpId)
and your stored procedure should be like this:
CREATE PROCEDURE [dbo].[sp_ZebraGetEmpName]
#EmpId int,
#EmpName varchar(40) out
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET #EmpName = (SELECT TOP 1 EmployeeName
FROM ZebraPrinter.dbo.EmployeeInfo
WHERE EmpID = #EmpId)
END
GO
Returning something, setting an output parameter value, and selecting something are three different things.
You can set #EmpName like NoDisplayName's answer and leave your C# code as-is, or you can just run the select and pull the value when you execute the query:
CREATE PROCEDURE [dbo].[sp_ZebraGetEmpName]
#EmpId int
AS
BEGIN
SELECT EmployeeName
FROM ZebraPrinter.dbo.EmployeeInfo
WHERE EmpID = #EmpId
END
string empName = (string)cmd.ExecuteScalar();
What you're seeing in Management Studio when you run this is not the return value, but rather the query result. The return value of your query would be null.

Return bigint from SQL Server stored procedure

I have written a stored procedure in SQL Server which will return a Bigint value
alter procedure [dbo].adding
#one bigint,
#two bigint,
#startid bigint output
as
begin
set #startid = #one + #two
return #startid
end
But while returning value I am getting an exception
Arithmetic overflow error converting expression to data type int
Can any one please help me to solve this issue?
Thanks in advance
Note : Above query is not the exactly the same procedure which i am using
UPDATED :
I have a code like below
_lookupId = cmdInsert.Parameters.Add("RetVal", SqlDbType.BigInt);
_lookupId.Direction = ParameterDirection.ReturnValue;
_procIn01 = cmdInsert.Parameters.Add("#idCount", SqlDbType.VarChar, 500);
cmdInsert.Parameters["#idCount"].Value = idCount;
_procIn01.Direction = ParameterDirection.Input;
_procIn02 = cmdInsert.Parameters.Add("#requestFrom", SqlDbType.VarChar, 100);
cmdInsert.Parameters["#requestFrom"].Value = clientId;
_procIn02.Direction = ParameterDirection.Input;
_pramOut = cmdInsert.Parameters.Add("#startID", SqlDbType.BigInt);
_pramOut.Direction = ParameterDirection.Output;
cmdInsert.ExecuteScalar();
With out returning the value how can i assign the value to "RetVal" my _lookup variable.
Procedures return a status value, which is always an integer. You can return the value from the stored procedure just by setting it:
alter procedure [dbo].adding
-- add the parameters for the stored procedure here
#one bigint,
#two bigint,
#startid bigint output
as
begin
-- set nocount on added to prevent extra result sets from
-- interfering with select statements.
set #startid = #one + #two
end;
Use return for whether or not the stored procedure succeeds.
You could call this with something like:
declare #startid bigint;
exec dbo.adding(1, 2, #startid output);
select #startid;
This error occurred because your return but you must using set to set a variable or using select
Set #outputvalue=#val1+#val2
Or
Select #outputvalue=#val1+#val2
Sotred procedure return answer is integer number that show sp successed or not
you can not use it for getting an big int number
if you want get a output value with out output parameter then you can use select with out variable, for example,
calling
Select #val1+#val2
now for get output using Execute Scalar method of command.

get the id of the last inserted row in

I saw few solutions here but none worked. I tried SCOPE_IDENTITY() didn't wotk. the id is autoincrement.
This is my stored procedure
CREATE PROCEDURE [dbo].[uploadVid]
#video varbinary(MAx),
#vidTitle varchar(50),
#vidCategory varchar(50),
#vidDate date,
#vidDescription varchar(Max),
#vidName varchar(50),
#vidSize bigint
AS
INSERT INTO Video(video, vidTitle, vidCategory, vidDate, vidDescription, vidName, vidSize)
VALUES (#video, #vidTitle, #vidCategory, #vidDate, #vidDescription, #vidName, #vidSize)
& in the back end I tried
Object i = register.ExecuteScalar();
&
int newId = (Int32)register.ExecuteScalar();
I put a break point and it gave me a value of null or 0. any help appreciated
Thanks
try this
CREATE PROCEDURE [dbo].[uploadVid]
#video varbinary(MAx),
#vidTitle varchar(50),
#vidCategory varchar(50),
#vidDate date,
#vidDescription varchar(Max),
#vidName varchar(50),
#vidSize bigint
AS
begin
declare #id as int --assuming your identity column is int
INSERT INTO Video(video, vidTitle, vidCategory, vidDate, vidDescription, vidName, vidSize)
VALUES (#video, #vidTitle, #vidCategory, #vidDate, #vidDescription, #vidName, #vidSize)
set #id = scope_identity()
select #id --return the value for executescaler to catch it
end
Probably you don't execute the commands in the correct sequence: (supposing you are using an SQL Server DB)
SqlCommand cmd = new SqlCommand("uploadVid", connnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(.....)
......
// After adding the parameters you execute the command to insert the new row....
int rowsInserted = cmd.ExecuteNonQuery();
if(rowsInserted > 0)
{
SqlCommand cmd1 = new SqlCommand("SELECT SCOPE_IDENTITY()", connection);
int newID = (int)cmd1.ExecuteScalar();
}
ExecuteScalar returns only the value of the first row in the first column of the query executed. In case of an insert this value is meaningless. You need an ExecuteNonQuery that returns the rows inserted by the command. After that run a new command with the SELECT SCOPE_IDENTITY() command text with the ExecuteScalar. This, of course, if you cannot modify the SP, the answer from th1rdey3 is better if you could change the proc because it avoids a run-trip to the database.

Stored procedure not inserting using cursor data in SQL Server

I am creating a web page to store data which is read from a Microsoft Excel worksheet.
I am passing the data to a stored procedure in SQL Server 2008.
Here is my C# code:
SqlConnection conn = new SqlConnection(AppDB);
conn.Open();
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_ins_TaskDetails_from_Excel";
command.Parameters.AddWithValue("#TaskDetails", dtTaskDetailsFromExcel);
string sReturnValue = command.ExecuteNonQuery().ToString();
The stored procedure has one user defined table data type as parameter.
Here is my stored procedure:
ALTER PROCEDURE dbo.sp_ins_TaskDetails_from_Excel
(
#TaskDetails TypeInsertTaskFromExcel11 readonly
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE
#ProjectID int,
#ProjectTeamID int,
#TeamLeaderUserID int,
#TaskCategoryName varchar(max),
#TaskDescription varchar(max),
#TeamMemberUserID int,
#TaskPriorityName varchar(10),
#PlanDuration float,
#PlanStartDate datetime,
#PlanEndDate datetime,
#TaskTypeName varchar(30),
#TaskStatusName varchar(30),
#TaskAllotName varchar(10),
#CreatedBy varchar(30),
#CreatedDate datetime,
#ISMailSend bit,
#Isvisible bit,
#UniqueID int
DECLARE TMSTaskDetailFromExcelCursor CURSOR FOR SELECT
ProjectID,
ProjectTeamID,
TeamLeaderUserID,
TaskCategoryName,
TaskDescription,
TeamMemberUserID,
TaskPriorityName,
PlanDuration,
PlanStartDate,
PlanEndDate,
TaskTypeName,
TaskStatusName,
TaskAllotName,
CreatedBy,
CreatedDate,
ISMailSend,
Isvisible,
UniqueID
FROM #TaskDetails
OPEN TMSTaskDetailFromExcelCursor
FETCH NEXT FROM TMSTaskDetailFromExcelCursor INTO
#ProjectID,
#ProjectTeamID,
#TeamLeaderUserID,
#TaskCategoryName,
#TaskDescription,
#TeamMemberUserID,
#TaskPriorityName,
#PlanDuration,
#PlanStartDate,
#PlanEndDate,
#TaskTypeName,
#TaskStatusName,
#TaskAllotName,
#CreatedBy,
#CreatedDate,
#ISMailSend,
#Isvisible,
#UniqueID;
WHILE ##FETCH_STATUS=0 BEGIN
-- Insert statements for procedure here
INSERT INTO ManageTasks (ProjectID, ProjectTeamID, TeamLeaderUserID,
TaskCategoryName,TaskDescription, TeamMemberUserID, TaskPriorityName,
PlanDuration, PlanStartDate, PlanEndDate, TaskTypeName,
TaskStatusName, TaskAllotName, CreatedBy, CreatedDate, ISMailSend, Isvisible,UniqueID)
VALUES (#ProjectID, #ProjectTeamID, #TeamLeaderUserID, #TaskCategoryName,
#TaskDescription, #TeamMemberUserID, #TaskPriorityName, #PlanDuration,
#PlanStartDate, #PlanEndDate, #TaskTypeName, #TaskStatusName,
#TaskAllotName, #CreatedBy, #CreatedDate, #ISMailSend,#Isvisible,#UniqueID);
FETCH NEXT FROM TMSTaskDetailFromExcelCursor INTO
#ProjectID,
#ProjectTeamID,
#TeamLeaderUserID,
#TaskCategoryName,
#TaskDescription,
#TeamMemberUserID,
#TaskPriorityName,
#PlanDuration,
#PlanStartDate,
#PlanEndDate,
#TaskTypeName,
#TaskStatusName,
#TaskAllotName,
#CreatedBy,
#CreatedDate,
#ISMailSend,
#Isvisible,
#UniqueID;
END;
CLOSE TMSTaskDetailFromExcelCursor;
DEALLOCATE TMSTaskDetailFromExcelCursor;
END
It receives the data and using a cursor in the same stored procedure each row will be inserted using an Insert statement in the same procedure.
While executing, all the data from Excel is passed to the stored procedure as exactly mentioned in the user defined table type.
But, the values are not stored in database and the stored procedure returns -1.
All the values are in correct format and order. I don't know what is going wrong.
Is there something I should change in the stored procedures?

Categories

Resources