Getting stored procedures multiple result - c#

I have a stored procedure which returns new ids.
create proc [dbo].[WriteIT]
(#deg nvarchar(max))
as
DECLARE #s nvarchar(max)
set #s = 'INSERT INTO test OUTPUT inserted.ID VALUES '
set #s += #deg
exec (#s)
How can I get that multiple results of stored procedures into a int[]?
string con = "Server=.;Database=Adb;Trusted_Connection=True";
SqlConnection connet = new SqlConnection(con);
SqlCommand cm = new SqlCommand("WriteIT", connet);
cm.CommandType = System.Data.CommandType.StoredProcedure;
bd = new StringBuilder();
string veri = "({0}),";
string sablon = "'{0}','{1}'";
for (int i = 0; i < 50; i++)
{
bd.Append(string.Format(veri, string.Format(sablon, new Random().Next(0, 100000).ToString(), new Random().Next(0, 100000).ToString())));
}
cm.Parameters.AddWithValue("#deger", bd.ToString().Substring(0, bd.Length - 1));
if (connet.State == System.Data.ConnectionState.Closed)
connet.Open();
string a = cm.ExecuteScalar();

ExecuteScalar is meant to return only the first column of the first row from the result..
If your SProc would return more than one value, you could use the ExecureReader() method.
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
You should also read on Random class. You should use the same instance to generate numbers.

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Usp_CRMEntryInsert]
#custnam nvarchar(250),
#proj nvarchar(255),
#projid int,
#contact nvarchar(100),
#updfile nvarchar(150),
#vtype nvarchar(100),
#sts varchar(15),
#recsts varchar(1),
#entryid int,
#entrydate datetime,
#dataentrydate datetime
AS
BEGIN
SET NOCOUNT ON;
insert into CRMEntry (custnam,Proj,projid,contact,updfile,vtype,status,rec_status,entered_id,entered_date,entry_date) values (#custnam,#proj,#projid,#contact,#updfile,#vtype,#sts,#recsts,#entryid,#entrydate,#dataentrydate)
select scope_identity()
This Scope_identity() return max value
maxid = cmd.ExecuteScalar()

Related

How to get the return value of a stored procedure?

I have the following stored procedure and I want to obtain the value that it returns:
ALTER PROCEDURE [dbo].[ExistsItemID]
#ItemID uniqueidentifier
AS
BEGIN
IF (EXISTS (SELECT ItemID FROM Discounts WHERE ItemID = #ItemID))
BEGIN
RETURN 1
END
ELSE
BEGIN
RETURN 0
END
END
And in C# I have the following code:
using (SqlConnection sqlCon = new SqlConnection(scheduleConnection.ConnectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("ExistsItemID", scheduleConnection);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.ExecuteScalar();
SqlParameter returno = new SqlParameter();
returno.Direction = ParameterDirection.ReturnValue;
int valor = returno.Value;
}
But it has not worked for me, how can I get the value of the stored procedure? First of all, thanks
You need to add the parameter to the command before executing it. Use the Add method on the Parameters collection.
using (SqlConnection sqlCon = new SqlConnection(scheduleConnection.ConnectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("ExistsItemID", scheduleConnection);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter returno = new SqlParameter();
returno.Direction = ParameterDirection.ReturnValue;
sqlCmd.Parameters.Add(returno);
sqlCmd.ExecuteScalar();
int valor = returno.Value;
}

A SqlParameter with parameter name '#name' is not contained by this SqlParameterCollection function

I am trying to return a value from the code below but I am getting an error that says:
A SqlParameter with parameter name '#vRESULT' is not contained by this SqlParameterCollection
c# Code:
public int userLogin()
{
string connStr = ConfigurationManager.ConnectionStrings["conn"].ToString();
string cmdStr = #"fucn_LOg";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
try
{
conn.Open();
cmd.CommandText = cmdStr;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters[":vResult"].Direction = ParameterDirection.Output;
cmd.Parameters.Add(new SqlParameter("param1", SqlDbType.VarChar)).Value = TB_1.Text;
cmd.Parameters.Add(new SqlParameter("param2", SqlDbType.VarChar)).Value = TB_2.Text;
cmd.ExecuteScalar();
return Int32.Parse(cmd.Parameters[":vResult"].Value.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return -1;
}
}
}
the sql server function code below with returning parameter DECLARE #vResult int
CREATE FUNCTION USER_LOGIN(#USER_NAME VARCHAR(60),
#PWD VARCHAR(60))
RETURNS INT
AS BEGIN
DECLARE #vResult int
SELECT #vRESULT=COUNT(*)
FROM OPER
WHERE UPPER(UNAM)=UPPER(#USER_NAME)
AND PSW=#PWD
IF #vResult=1
SET #vResult=1
ELSE
SET #vResult= -1
RETURN #vResult
END
Just Get result from Stroed Procedure like this:
var result = cmd.ExecuteScalar();
return Int32.Parse(result.ToString());
This gets first and Only result from Stored Procedure.
Also recommend simplify your code Like this:
public int userLogin() {
string connStr = ConfigurationManager.ConnectionStrings["conn"].ToString();
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand("fucn_LOg", conn)) {
try {
cmd.Connection.Open();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#param1", TB_1.Text);
cmd.Parameters.AddWithValue("#param2", TB_2.Text);
var result = cmd.ExecuteScalar();
return Int32.Parse(result.ToString());
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
return -1;
}
finally {
if (cmd.Connection.State != ConnectionState.Closed) cmd.Connection.Close();
}
}
}
And your Stored procedure should looks Like this:
CREATE PROCEDURE fucn_LOg
(
#param1 nvarchar(max),
#param2 nvarchar(max)
)
AS
BEGIN
SET NOCOUNT ON;
if (exists(select * from tbUsers where flLogin = #param1 and flPassword = #param2))
begin
return 1;
end
else
begin
return 0;
end
END
GO
OR
CREATE PROCEDURE fucn_LOg
(
#param1 nvarchar(max),
#param2 nvarchar(max)
)
AS
BEGIN
SET NOCOUNT ON;
select COUNT(*) from tbUsers where flLogin = #param1 and flPassword = #param2
END
GO
Several problems.
First, you don't need the cmd.Parameters.Clear();, as you just establish a new cmd.
Second, use # for SQL Server parameters.
Third, a parameter named vResult is not set, so cmd.Parameters[":vResult"].Direction is invalid. You need to assign its type and value. Make sure your stored procedure has this parameter set with correct SQL data type.
Lastly, I guess you return the vResult in your stored procedure like select #vResult; so make it a new vResult = function(vResult). But no, it is not how SQL Server work. It won't change your input parameter even though you return your #vResult. While, ExecuteScaler does. So, simply get your result back by var result = cmd.ExecuteScalar();.
You are getting data from a stored procedure, not getting back the parameter you sent. That's the supposed correct way.
conn.Open();
cmd.CommandText = cmdStr;
cmd.CommandType = CommandType.StoredProcedure;
//Base on sql you provided, it is no need for this part.
/*
SqlParameter vResult = new SqlParameter();
vResult.ParameterName = "#vResult";
vResult.Direction = ParameterDirection.Output;
vResult.SqlDbType = System.Data.SqlDbType.???;
vResult.Value = ???;
cmd.Parameters.Add(vResult);
*/
cmd.Parameters.Add("#param1", SqlDbType.VarChar).Value = TB_1.Text;
cmd.Parameters.Add("#param2", SqlDbType.VarChar).Value = TB_2.Text;
var result = cmd.ExecuteScalar();
return Int32.Parse(result.ToString());
This is hard to debug without the SP, but a couple of things jump out.
First, you need to use the '#' character as a prefix for your parameter names, not a colon.
Second, you should define your output parameter like this:
SqlParameter outputParam = new SqlParameter("#vResult", SqlDbType.Int);
outputParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outputParam);

No value was supplied, to Output Parameter

I am getting error as "Procedure or function 'Artical_i' expects parameter '#ID', which was not supplied.". But my #ID parameter is Output parameter.
-------------------------------c# Code----------------------------------------
int retVal=0;
SqlParameter outputParam = new SqlParameter();
outputParam.ParameterName = "#ID";
outputParam.SqlDbType = SqlDbType.Int;
outputParam.Direction = ParameterDirection.Output;
outputParam.Value = retVal; /// Added in Edit
SqlParameter[] sParam =
{
outputParam,
new SqlParameter("#Title",this.Title),
new SqlParameter("#BaseUri",this.BaseUri),
new SqlParameter("#Description",this.Description),
new SqlParameter("#ShortDescription",this.ShortDescription),
new SqlParameter("#Copyright",this.Copyright),
new SqlParameter("#ItemID",this.ItemID),
new SqlParameter("#LastUpdatedTime",this.LastUpdatedTime),
new SqlParameter("#PublishDate",this.PublishDate),
new SqlParameter("#SourceFeedURL",this.SourceFeedURL)
};
SqlConnection connection = new SqlConnection(connectionString)
SqlCommand command = new SqlCommand();
connection.Open();
command.Connection = connection;
command.CommandText = procedureName;
command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter p in sParam )
{
command.Parameters.AddWithValue(p.ParameterName, p.Value);
}
command.ExecuteNonQuery(); /// Error Here as "Procedure or function 'Artical_i' expects parameter '#ID', which was not supplied."
retVal = Convert.ToInt32(outputParam.Value); // Value returned as 0 here
-------------------- Stored Procedure---------------------------
IF OBJECT_ID (N'Artical_i', N'P') IS NOT NULL
Begin
drop procedure Artical_i
End
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Procedure Artical_i
(
#Title nvarchar(500),
#BaseUri nvarchar(2083),
#Description nvarchar(max),
#ShortDescription nvarchar(500),
#Copyright nvarchar(250),
#ItemID varchar(250),
#LastUpdatedTime datetimeoffset(7),
#PublishDate datetimeoffset(7),
#SourceFeedURL nvarchar(2083),
#ID int OUTPUT
)
as
Begin
BEGIN TRY
BEGIN TRANSACTION
set nocount on;
INSERT INTO [dbo].[Artical]
([Title]
,[BaseUri]
,[Description]
,[ShortDescription]
,[Copyright]
,[ItemID]
,[LastUpdatedTime]
,[PublishDate]
,[CreatedDate]
,[SourceFeedURL])
VALUES
(#Title,
#BaseUri,
#Description,
#ShortDescription,
#Copyright,
#ItemID,
#LastUpdatedTime,
#PublishDate,
Getdate(),
#SourceFeedURL)
Select #ID =SCOPE_IDENTITY()
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
Select #ID =0
END CATCH
End
GO

MySQL. insert into stored procedure affected rows' count is always 0

I call a stored procedure from my c# code to insert a row into a table. My problem is that i always get 0 affected rows. Here are the codes
Stored procedure code
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `AddInfo`(
IN _activationDate datetime,
IN _organization varchar(100),
IN _email varchar(45),
IN _tableName varchar(35))
BEGIN
set #sqlquery = concat('insert into ', _tableName, ' values (?, ?, ?)');
prepare stmt from #sqlquery;
set #activationDate = _activationDate;
set #orgaization = _organization;
set #email = _email;
execute stmt using #activationDate, #orgaization, #email,;
deallocate prepare stmt;
END
C# code
using (MySqlConnection conn = new MySqlConnection(connStr))
{
string spName = "AddInfo";
MySqlCommand cmd = new MySqlCommand(spName, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#_activationDate", activationDate);
cmd.Parameters.AddWithValue("#_organization", organization);
cmd.Parameters.AddWithValue("#_email", email);
cmd.Parameters.AddWithValue("#_tableName", tableName);
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
bool added = rowsAffected == 1 ? true : false;
conn.Close();
return added;
}
when i run this code the row is successfully added to the table, but rowsAffected is always 0. Where is my problem? Thank you

how to pass ref variable to a SQL stored Procedure using ADO.NET?

i have that code using LINQ to call a stored procedure to save some data into database then return two variables from the stored procedure.
[ASP.NET code]
dbDataContext dbo = new dbDataContext();
dbo.AddNewDoctor(doctorName, email, password, ref DocId, ref result);
[SQL]
create PROCEDURE [dbo].[AddNewDoctor]
#doctorname nvarchar(100),
#email nvarchar(100),
#password nvarchar(MAX),
#docId int out,
#Result int out
AS
BEGIN
SET NOCOUNT ON;
declare #idCounter int
select #idCounter = count(*) from dbo.doctors
if EXISTS (select * from dbo.doctors where e_mail = #email)
begin
SET #Result = -1
set #docId= 0
end
else
begin
INSERT INTO [dbo].[doctors]
([doctor_id]
,[doctorname]
,[e_mail]
,[password]
VALUES
((#idCounter +1)
,#docotorname
,#email
,#password
)
SET #Result = 1
set #docId= (#idCounter + 1)
end
END
this code work very well what i want to do now to use ADO instead of LINQ, the problem with me is that i can't pass the ref variable as in LINQ so how can i do it using ADO
You'll have to do something like this. Use ParameterDirection
SqlParameter output = new SqlParameter(paramName, dbType);
output.Direction = ParameterDirection.Output;
command.Parameters.Add(output);
In your case you've to use SqlDbType.Int. Use Value property to read return value.
SqlParameter output = new SqlParameter(paramName, SqlDbType.Int);
output.Direction = ParameterDirection.Output;
command.Parameters.Add(output);
int Result = (int) output.Value; or int? Result = (int?) output.Value;
Try this
using (SqlConnection con = new SqlConnection("Your connection string"))
{
con.Open();
SqlCommand mycommand = new SqlCommand();
mycommand.Connection = con;
mycommand.CommandText = "dbo.AddNewDoctor";
mycommand.CommandType = CommandType.StoredProcedure;
mycommand.Parameters.AddWithValue(doctorName);
mycommand.Parameters.AddWithValue(email);
mycommand.Parameters.AddWithValue(password);
mycommand.Parameters.AddWithValue(ref DocId);
mycommand.Parameters.AddWithValue(ref result);
mycommand.ExecuteNonQuery();
}
Hope this helps thanks.
Refer to this article, there is an working example:
http://csharp-guide.blogspot.de/2012/05/linq-to-sql-call-stored-procedure-with_25.html

Categories

Resources