how to get the auto generated values from sql using c#? - sql

I have an Stored Procedure like below..
CREATE PROCEDURE [dbo].[spMYSPDetails]
#Id VarChar(6),
#Name VarChar(50),
#Limit Money,
#Status VarChar(1),
#Accounts As SmallInt
AS BEGIN
IF(LEN(ISNULL(#strDebtorId, '')) = 0) BEGIN
WHILE 0 = 0 BEGIN
SET #Id = '9' + dbo.fnGenerateRandomCode(5, '0123456789')
IF NOT EXISTS (SELECT 1 FROM mytbl WITH (NOLOCK) WHERE s_Id = #Id) BEGIN
INSERT INTO Mytbl
(D_Id,
D_Name,
D_Limit,
D_Status,
D_Accounts,
D_dtmStamp,
D_Balance)
VALUES
(#Id,
#Name,
#Limit,
#Status,
#Accounts,
GETDATE(),
#Limit)
BREAK
END
I have c# sharp code to call this SP like this...
try
{
string Id = "";
if (hdDId.Value.ToString() != "")
{
Id = hdDId.Value.ToString();
}
objDB.blnParamClear();
objDB.blnParamAdd(ParameterDirection.Input, "#Id", SqlDbType.VarChar, 6, Id.ToString());
objDB.blnParamAdd(ParameterDirection.Input, "#Name", SqlDbType.VarChar, 50, txtName.Value.ToString());
objDB.blnParamAdd(ParameterDirection.Input, "#Limit", SqlDbType.Money, 8, decimal.Parse(txtLimit.Value.ToString()));
objDB.blnParamAdd(ParameterDirection.Input, "#Status", SqlDbType.VarChar, 1, cboStatus.Value);
objDB.blnParamAdd(ParameterDirection.Input, "#intMaxAccounts", SqlDbType.SmallInt, 4, txtAccnts.Value.ToString());
blnResult = (objDB.lngExecuteSP("spMYSPDetails") == 0);
}
Now I want to catch that auto generated(random) ID in C# for my reference. I tried but am unable to Catch.. Is there any way to catch the same id that is generated by SP in SQL.Suggest me something...

Use your #ID as output variable.
#Id VarChar(6) output
Then set your C# parameter
SqlParameter paramOutput = new SqlParameter("#Output", SqlDbType.nVarChar);
paramOutput.Direction = ParameterDirection.Output;

Stored procedures can have return values and output parameters in addition to input parameters.
Use an Output Parameter.
Change ParameterDirection.Input to ParameterDirection.Output when defining a param "#Id".
PS. What are you passing right now to the sproc (Id.ToString()) if the id is generated in the DB? Why aren't you just using autoincrement column?

Related

Fetch stored procedure value

I have a table RhSeq which contains the following columns:
ScoTable (PK, varchar(20),not NULL)
ScoColonne (PK, varchar(50), not NULL)
ScoSequence (int, not NULL)
ScoDescription (varchar(100), not NULL)
I have a stored procedure which, given ScoTable and ScoColonne, increments ScoSequence and returns the incremented ScoSequence value:
EDITED - Here's the full stored procedure
CREATE PROCEDURE [dbo].[usp_RhSeqNextVal]
#table VARCHAR (20), #colonne VARCHAR (30), #sequence_id INT OUTPUT
AS
SET NOCOUNT ON
SET #sequence_id = -1
DECLARE #transaction AS BIT
SET #transaction = 0;
IF 0 = ##TRANCOUNT
BEGIN
BEGIN TRAN
SET #transaction = 1;
END
UPDATE dbo.RhSeq
SET ScoSequence = CASE WHEN Right(#colonne,1) = '-' THEN
ScoSequence - 1
ELSE
ScoSequence + 1
END
WHERE ScoTable = #table
AND ScoColonne = #colonne
SELECT #sequence_id = ScoSequence
FROM dbo.RhSeq
WHERE ScoTable = #table
AND ScoColonne = #colonne
IF 1 = #transaction
BEGIN
COMMIT TRAN
END
In Visual Studio, if I right click on the stored procedure (in Server Explorer) and choose 'Execute', I enter values for ScoTable and ScoColonne and set sequence_id to null and it executes fine, returning the new incremented sequence_id value. So no problem with the stored procedure.
The problem I have is when I try to get the returned sequence_id inside my code.
SqlParameter param1 = new SqlParameter("#ScoTable", "MyTable");
SqlParameter param2 = new SqlParameter("#ScoColonne", "MyColumn");
SqlParameter param3 = new SqlParameter("#sequence_id", DBNull.Value);
var numeroSequence = db.Database.SqlQuery<RhSeq>("usp_RhSeqNextVal #ScoTable,#ScoColonne, #sequence_id", param1, param2,param3).ToList();
I get an error
System.Data.Entity.Core.EntityCommandExecutionException: A member of the type, 'ScoTable', does not have a corresponding column in the data reader with the same name
From my understanding, the error comes from RhSeq, since the stored procedure returns only sequence_id, which is an int, it cannot create a RhSeq object with it. I try to cast the result to an int, but it's still not working.
How can I store the sequence_id returned by the stored procedure into my var numeroSequence?
Had a similar issue in LinqToSQL. Selecting #sequence_id in the procedure after setting it did the job:
In your SP after:
SELECT #sequence_id = ScoSequence
FROM dbo.RhSeq
WHERE ScoTable = #table
AND ScoColonne = #colonne
Add:
SELECT #sequence_id
And then of course:
db.Database.SqlQuery<int>...

How to use the return value of stored procedure in asp.net?

I use this stored procedure for get the number of records
ALTER PROCEDURE [dbo].[Asbabbazi_A]
#count int output
AS
BEGIN
if(#count=0)
set #count =( select count(*) from dbo.Table_asbabbazi where (active= 0))
end
now I want use the #count in my project.I wrote this codes for use the #count in method.
SqlConnection con = new SqlConnection(constr);
cmd.Connection = con;
con.Open();
DataAdapter.SelectCommand = cmd;
DataSet ds = new DataSet("haftehbazardb");
SqlCommandBuilder bldr = new SqlCommandBuilder(DataAdapter);
SqlParameter returnParameter = cmd.Parameters.Add("count", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
DataAdapter.Fill(ds, Table_asbabbazi);
countrecords = (int)returnParameter.Value;
this codes have no error but when i use the (countrecords ) in my project the value of (countrecords ) is zero that is not right .
Please help
If you want to get the value as the output of the stored procedure, you will need to return it.
ALTER PROCEDURE [dbo].[Asbabbazi_A]
#count int output
AS
BEGIN
if(#count=0)
set #count =( select count(*) from dbo.Table_asbabbazi where (active= 0))
return #count
end
You are confusing output parameters with a return value.
Return value is generally used to indicate the status of your procedure, it will be 0 if not specified, e.g.
CREATE PROCEDURE dbo.TestProc #Out INT OUTPUT
AS
BEGIN
BEGIN TRY
SET #Out = 1 / 0;
RETURN 0;
END TRY
BEGIN CATCH
SET #Out = 0;
RETURN 1;
END CATCH
END
Then calling this with T-SQL;
DECLARE #out INT, #return INT;
EXECUTE #Return = dbo.TestProc #out OUT;
SELECT [Return] = #return, [out] = #out;
Will give:
Return | out
-------+-----
1 | 0
Since 0 is the default return value, this is why you are getting 0 out from returnParameter, you need to use ParameterDirection.Output:
SqlParameter returnParameter = cmd.Parameters.Add("count", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.Output;

Additional information: Procedure or function 'spCustomerRegistration' expects parameter '#other', which was not supplied

I am trying to insert data into an MS SQL database table and gets this error when the other field is empty
The Other Column has Allow Nulls set to true
Additional information: Procedure or function 'spCustomerRegistration' expects parameter '#other', which was not supplied.
Model Code
SqlCommand cmd = new SqlCommand("spCustomerRegistration", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#firstname", txtFirstName);
cmd.Parameters.AddWithValue("#lastname", txtLastName);
cmd.Parameters.AddWithValue("#stateid", ddLocation1);
cmd.Parameters.AddWithValue("#urbanrural", txtStatUR);
cmd.Parameters.AddWithValue("#cityid", city_id);
cmd.Parameters.AddWithValue("#areaid", area_id);
cmd.Parameters.AddWithValue("#streetid", street_id);
cmd.Parameters.AddWithValue("#townid", town_id);
cmd.Parameters.AddWithValue("#villageid", village_id);
cmd.Parameters.AddWithValue("#houseno", txtHouseNo);
cmd.Parameters.AddWithValue("#dob", Convert.ToDateTime(DOB));
cmd.Parameters.AddWithValue("#customeremail", txtEmail);
cmd.Parameters.AddWithValue("#customerphone", _phone_number);
cmd.Parameters.AddWithValue("#gender", ddGender);
cmd.Parameters.AddWithValue("#password", dal.Encryptdata(txtPassword));
cmd.Parameters.AddWithValue("#customeripaddress", _cip);
cmd.Parameters.AddWithValue("#regcode", _regcode);
cmd.Parameters.AddWithValue("#customerguid", _CustomerGuid);
cmd.Parameters.AddWithValue("#other", txtOthers);
cmd.Parameters.Add("#retval", SqlDbType.Int);
cmd.Parameters["#retval"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#userid", SqlDbType.Int, 0, "id");
cmd.Parameters["#userid"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
retval = (int)cmd.Parameters["#retval"].Value;
pk_uid = (int)cmd.Parameters["#userid"].Value;
con.Close();
Stored Procedure
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT * FROM CustomerRegistration WHERE CustomerEmail =#customeremail or CustomerPhone=#customerphone )
BEGIN
INSERT INTO CustomerRegistration (FirstName ,LastName ,StateID, Urban_Rural, CityID, AreaID, StreetID, TownID, VillageID, HouseNo, DOB, CustomerEmail, CustomerPhone, Gender, Password, CustomerIPAddress, RegCode, CustomerGuid, Other ) VALUES (#firstname, #lastname, #stateid, #urbanrural, #cityid, #areaid, #streetid, #townid, #villageid, #houseno, #dob, #customeremail, #customerphone, #gender, #password, #customeripaddress, #regcode, #customerguid, #other )
SELECT #userid = SCOPE_IDENTITY();
SET #retval=1
END
ELSE
BEGIN
SET #retval =0
SET #userid =0
END
Sql server does not support null. when any object or value is null then you have to assign value DBNull.Value instead of null.

Retrieving output parameter from stored procedure with oledb command vb.net

My stored procedure:
PROCEDURE [dbo].[addMasterTransaksi]
#kodeSuplier varchar(10),
#Total money,
#kodeUser varchar(10),
#isLunas varchar (2),
#Dp money,
#kodeTrans varchar(10) output
AS
BEGIN
Declare #KdTrans as varchar(10);
Declare #Kode as int;
Declare #thisYear as varchar(10);
select #thisyear = RIGHT(YEAR(getDate()),2)
SELECT TOP(1) #KdTrans = SUBSTRING(kodeTransaksi,5,6) FROM TblMasterPembelian WHERE YEAR(Tanggal) = YEAR(getDate()) order by kodeTransaksi desc;
--print #KdTrans
IF #KdTrans IS Null
SET #KdTrans = 'TB'+ #thisYear +'000001'
else
begin
select #Kode = convert(int,#KdTrans);
select #Kode = #Kode + 1;
select #KdTrans = convert(int,#Kode);
select #KdTrans = '00000' + #KdTrans;
select #KdTrans = right(#KdTrans,6)
select #KdTrans ='TB' + #thisYear + #KdTrans
end
SET NOCOUNT ON;
--ke Master Pembelian
INSERT INTO TblMasterPembelian(kodeTransaksi,Tanggal,Total,kodeSuplier,kodeUser,isLunas,DP)
VALUES (#KdTrans,getDate(),#Total,#kodeSuplier,#kodeUser,#isLunas,#Dp)
set #kodeTrans =#KdTrans
--print #kodeTrans
return #kodetrans
END
VB.NET code:
Public Function addMasterPembelianny(ByVal kodesup As String, ByVal total As Long, ByVal kodeUser As String, ByVal isLunas As String, ByVal dp As Long)
Dim kodeTransaksi As String
modKoneksi.bukaKoneksi()
command.Connection = modKoneksi.koneksidb
command.CommandType = CommandType.StoredProcedure
command.CommandText = "addMasterTransaksi"
command.Parameters.Add("#kodeSuplier", OleDbType.VarChar, 10, ParameterDirection.Input).Value = kodesup
command.Parameters.Add("#Total", OleDbType.BigInt, 10, ParameterDirection.Input).Value = total
command.Parameters.Add("#kodeUser", OleDbType.VarChar, 10, ParameterDirection.Input).Value = kodeUser
command.Parameters.Add("#isLunas", OleDbType.VarChar, 2, ParameterDirection.Input).Value = isLunas
command.Parameters.Add("#Dp", OleDbType.BigInt, 10, ParameterDirection.Input).Value = dp
command.Parameters.Add("#kodeTrans", OleDbType.Char, 10)
command.Parameters("#kodeTrans").Direction = ParameterDirection.Output
command.ExecuteReader()
kodeTransaksi = command.Parameters("#kodeTrans").Value
modKoneksi.tutupKoneksi()
Return kodeTransaksi
End Function
I have problem when I want to retrieve parameter from a stored procedure..
When I run that code, there appear an error like this message ..
Conversion failed when converting the varchar value 'TB13000005' to data type int.
Why they said that failed converting to data type int??
What's wrong with my code..?
master help me please..
I believe it is this line in your stored procedure which is causing the error:
return #kodetrans
Stored procedures can only return integers as part of the RETURN statement so the line fails (as #kodetrans is a VARCHAR). You can just remove that line completely...For output parameters, what you have done here:
set #kodeTrans =#KdTrans
In the stored proc is fine and should be sufficient/OK.

get return value from stored procedure without output parameter

I have a vb.net application that inserts records into a db table using a stored procedure that is supposed to return a value. This stored procedure was setup by someone else and initially was linked to a webservice through which my application made the insert and got the return value in the returned xml. I now have access to the db table and not sure how to receive the return value in my vb.net method.
SQl stored procedure snippet;
#urlname varchar(500),
#siteid varchar(16),
#origin varchar(50),
#queryid varchar(25)
AS
SET NOCOUNT ON;
declare #cnt int
declare #serverip varchar(16)
declare #mincnt int
declare #siteservercnt int
select #cnt=COUNT(*) from sites
where urlname=#urlname
if #cnt = 0
begin
insert into sites (urlname,siteid,exported,origin,queryid)
values(#urlname,#siteid,1,#origin,#queryid)
select #siteservercnt = COUNT(*) from siteserverip where siteid=#siteid
if #siteservercnt=0
begin
select top 1 #mincnt=COUNT(*),#serverip=serverip from siteserverip
group by serverip
order by COUNT(*)
select top 1 #mincnt=sitecount,
#serverip=serverip from serveripcounts
order by sitecount
insert into siteserverip values(#siteid,#serverip)
update serveripcounts set sitecount=sitecount+1
where serverip=#serverip
end
end
SELECT siteid from sites
where urlname=#urlname
return
and my vb.net code to do the insert
CommandObj.CommandText = "Getsite"
CommandObj.CommandTimeout = 90
Dim newUrl As String = String.Empty
CommandObj.Parameters.Clear()
Dim m_param As SqlParameter
m_param = CommandObj.Parameters.Add("#urlname", SqlDbType.VarChar, 500)
m_param.Direction = ParameterDirection.Input
m_param.Value = name
m_param = CommandObj.Parameters.Add("#siteid", SqlDbType.VarChar, 16)
m_param.Direction = ParameterDirection.Input
m_param.Value = siteid
m_param = CommandObj.Parameters.Add("#origin", SqlDbType.VarChar, 50)
m_param.Direction = ParameterDirection.Input
m_param.Value = method
m_param = CommandObj.Parameters.Add("#queryId", SqlDbType.VarChar, 25)
m_param.Direction = ParameterDirection.Input
m_param.Value = forumID
Dim recordsAffected As Integer = CommandObj.ExecuteNonQuery
You can use ExecuteScalar to get that value. ExecuteNonQuery returns number of rows affected while you want to get the value generated by last select. You could use ExecuteReader as well but that is useful when your SP might be returning more columns and/or more rows.
'Populate first column and first row value in siteID
Dim siteID As Integer = CommandObj.ExecuteScalar