ALTER PROCEDURE dbo.uspGetOrderTrackingHeaderInfo
#ContractID varchar(9)
, #SalesRepID int
, #StatusID int
, #TypeID int
, #StartDate datetime
, #EndDate datetime
, #Identity int = null output
AS
INSERT INTO [dbo].[tblOrderTracking]
([ContractID]
,[StatusID]
,[TypeID]
,[SalesRepID]
,[StartDate]
,[EndDate])
VALUES
(#ContractID
,#StatusID
,#TypeID
,#SalesRepID
,#StartDate
,#EndDate)
SET #Identity = Scope_Identity()
Using oConn As New SqlConnection(Me.Master.Master.AdminNetConnString)
Try
With cmd
.Connection = oConn
.CommandType = CommandType.StoredProcedure
.CommandText = "dbo.uspInsertOrderTrackingInfo"
.Parameters.AddWithValue("#ContractID", Session("#OrderContractID"))
.Parameters.AddWithValue("#SalesRepID", Integer.Parse(Me.ddlSalesRep.SelectedValue.ToString()))
.Parameters.AddWithValue("#StatusID", Integer.Parse(Me.ddlStatus.SelectedValue.ToString()))
.Parameters.AddWithValue("#TypeID", Integer.Parse(Me.ddlOrderType.SelectedValue.ToString()))
.Parameters.AddWithValue("#StartDate", CDate(txtStartDate.Text.Trim))
.Parameters.AddWithValue("#EndDate", CDate(txtEndDate.Text.Trim))
.Parameters.Add("#Identity", SqlDbType.Int, ParameterDirection.Output)
End With
oConn.Open()
cmd.ExecuteNonQuery()
Session("WorkingOrderID") = cmd.Parameters("#Identity").Value
Response.Redirect("OrderOverview.aspx")
Catch ex As Exception
Me.Master.Master.HandleException(ex, True, "An error occured while attempting to save the order setup information")
Finally
If Not cmd Is Nothing Then
cmd.Dispose()
End If
End Try
End Using
You have posted code for the proc "uspGetOrderTrackingHeaderInfo" and you are calling the proc "uspInsertOrderTrackingInfo". Perhaps you have modified the wrong proc and don't have the output on the Insert one.
Related
I have my stored procedure with an input parameter and an output parameter. I created parameters and was able to execute the job for the first time and received the output value in vJobstatus variable. When I triggered the stored procedure for a second time, I am getting NULL in cmd.Parameters("#vJobStatus").Value.
Please help me to get the value of output parameter. TestJob1 is triggered, but the output value is NULL.
Public pm As ADODB.Parameter
Public cnnStr, StrQuery, vJobName As String
Public RunStatus, vJobStatus As Integer
Global Flag_Chkbox As Integer
Set rs = New ADODB.Recordset
Set cmd = New ADODB.Command
cmd.ActiveConnection = cnn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "Run_SQL_Job"
cmd.CommandTimeout = 120
Set pm = New ADODB.Parameter
Set pm = cmd.CreateParameter("#vJobName", adVarChar, adParamInput, 50, "TestJob")
cmd.Parameters.Append pm
Set pm = cmd.CreateParameter("#vJobStatus", adInteger, adParamOutput, , vJobStatus)
cmd.Parameters.Append pm
cmd.Execute
vJobStatus = cmd.Parameters("#vJobStatus").Value
If vJobStatus <> 1 Then
cnn.Close
Application.Interactive = True
Application.StatusBar = ""
Exit Sub
Else
cmd.Parameters("#vJobName").Value = "TestJob1"
cmd.Execute
vJobStatus = cmd.Parameters("#vJobStatus").Value
CREATE PROCEDURE [dbo].[Run_SQL_Job]
#vJobName VARCHAR(50)
,#vJobStatus INTEGER OUTPUT
AS
DECLARE #vRunStatus as INT
DeclarE #vJobStats as INT
WAITFOR DELAY '00:00:5';
SET #vRunStatus = (SELECT Runstatus from [dbo].[VIEW])
WHILE #vRunStatus >= 1
BEGIN
SET #vRunStatus = (SELECT Runstatus from [dbo].[VIEW])
END
IF #vRunStatus = 0
BEGIN
EXEC msdb.dbo.sp_start_job #vJobname
WAITFOR DELAY '00:00:10';
END
SET #vRunStatus = (SELECT Runstatus from [dbo].[VIEW])
WHILE #vRunStatus >= 1
BEGIN
SET #vRunStatus = (SELECT Runstatus from [dbo].[VIEW])
END
SELECT #vJobStatus = run_status FROM msdb.dbo.sysjobhistory
where instance_id = (SELECT max(instance_id) from msdb.dbo.sysjobhistory where step_name = #vJobName)
GO
I have this stored procedure that executes fine:
ALTER PROCEDURE [dbo].[SP_GENERATETICKET]
#RESULT AS VARCHAR(255) OUTPUT
AS
BEGIN
DECLARE #D AS DATETIME = GETDATE()
DECLARE #LASTTICKET AS VARCHAR(50) ;
DECLARE #NUM AS VARCHAR(50);
SET #LASTTICKET=(SELECT TOP 1 TICKETNO FROM tblTicket WHERE
MONTH(ENTRYVEHICLE ) = MONTH(#D ) ORDER BY TICKETNO DESC);
IF (CONVERT(VARCHAR(10),YEAR(#D),110) <> CONVERT(VARCHAR(10),YEAR(GETDATE()),110))--IF YEAR IS DIFFERENT, RESET SERIES
BEGIN
SET #NUM = '1'
END
ELSE
BEGIN
IF ISNULL(#LASTTICKET,'1') = '1'--IF MONTH IS DIFFERENT, RESET SERIES
BEGIN
SET #NUM ='1'
END
ELSE
BEGIN
SET #NUM = CAST(CAST (RIGHT(#LASTTICKET,5) AS INT) + 1 AS VARCHAR)
END
END
SET #RESULT = RIGHT(CONVERT(VARCHAR(10),#D,101),2) + '-' + LEFT(CONVERT(VARCHAR(10),#D,101),2) + '-' + RIGHT('0000'+CAST(#NUM AS VARCHAR),5)
SELECT #RESULT
END
I have this Code but it returns null
SqlConnection con = new SqlConnection(gsql.connectionString);
SqlCommand command = new SqlCommand("SP_GENERATETICKET", con);
try
{
con.Open();
command.CommandType = CommandType.StoredProcedure;
SqlParameter result = command.Parameters.Add("#RESULT", SqlDbType.VarChar);
result.Direction = ParameterDirection.Output;
txtTicket.Text = (string)command.Parameters["#RESULT"].Value;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
What should I do?
there problem is there , you forgot to execute command
command.ExecuteNonQuery()
without executing command you want get result back.
also you forgot to add size for you varchar paramter , so add thing line
result.Size = 8000;
udpated in below code
you code will be , you need to use using to dispose things for you
using(SqlConnection con = new SqlConnection(gsql.connectionString))
{
using(SqlCommand command = new SqlCommand("SP_GENERATETICKET", con))
{
try
{
con.Open();
command.CommandType = CommandType.StoredProcedure;
SqlParameter result = command.Parameters.Add("#RESULT", SqlDbType.VarChar);
result.Size = 8000;//add parameter size
result.Direction = ParameterDirection.Output;
command.ExecuteNonQuery();//this line need to be added
txtTicket.Text = (string)command.Parameters["#RESULT"].Value;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Parameters are a good practice but for output you cannot have SQL injection (that I know of).
con.Open();
command.CommandType = CommandType.StoredProcedure;
txtTicket.Text = (string)command.ExecuteScalar();
For size you can use this syntax:
SqlParameter result = command.Parameters.Add("#RESULT", SqlDbType.VarChar, 800);
i am getting error of ExcecuteNonQuery ,i am not getting where i am wrong please help!
SqlConnection con = new SqlConnection(
"Data Source="";Initial Catalog=bunny;Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand("userpro", con);
CommandType cd = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Username", TextBox1.Text);
cmd.Parameters.AddWithValue("#Addresss", TextBox2.Text);
cmd.Parameters.AddWithValue("#Contact ", TextBox3.Text);
cmd.Parameters.AddWithValue("#EmailId", TextBox4.Text);
cmd.Parameters.AddWithValue("#Passwords", TextBox5.Text);
cmd.Parameters.AddWithValue("#ConfirmPassword", TextBox6.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this is my store procedure
create procedure userpro
#Username varchar (20),
#Addresss varchar (20),
#Contact varchar (20),
#EmailId varchar (20),
#Passwords varchar (20),
#ConfirmPassword varchar (20)
as
begin
if exists (select * from userlogs where Username=#Username)
begin
update userlogs set Addresss=#Addresss,Contact=#Contact,EmailId=#EmailId,Passwords=#Passwords,ConfirmPassword=#ConfirmPassword where Username=#Username
end
else
begin
insert into userlogs(Username,Addresss,Contact,EmailId,Passwords,ConfirmPassword) values (#Username,#Addresss,#Contact,#EmailId,#Passwords,#ConfirmPassword)
end
end
You need to check if TextBox1.Text is not null. If it is procedure will fail because #Username is mandatory. You can resolve this like that:
if(TextBox1.Text == null)
cmd.Parameters.AddWithValue("#Username", DBNull.Value);
else
cmd.Parameters.AddWithValue("#Username", TextBox1.Text);
Or you can make this parameter optional in your userpro procedure:
create procedure userpro
#Username varchar (20) = '',
I've been stumped with the following error for the past hour:
"Procedure or function 'write_call' expects parameter '#Date', which was not supplied."
The #date parameter is a smalldatetime. I am trying to pass the value #1/27/2009 04:32:00 PM#
I am using SQLExpress 2014.
The same stored proc has been in production on SQLExpress 2008
T-SQL Stored Proc:
ALTER proc [dbo].[write_call]
(
#Date smalldatetime, #Duration smallint, #Ring tinyint, #Extension smallint = null, #Number varchar(20) = null, #LineID smallint,
#AccountID smallint = null, #AccountName varchar(30) = null, #UnitID smallint = null, #UnitName varchar(30) = null, #AreaName varchar(100) = null, #CallType char(1) = null,
#CallCode varchar(6) = null, #Rate numeric(5,2) = 0.0, #Cost numeric(12,2) = 0.0, #TAC varchar(10) = null
)
as
declare #id int=0, #old_acctid int=0 --, #old_rate numeric(5,2)=0.0, #old_cost numeric(12,2)=0.0
select #id=o.ID,#old_acctid=o.AccountID from OutboundCalls o where o.Date=#Date and o.Duration=#Duration and o.Number=#Number
if #id=0
begin
insert into _OutboundCalls (Date, Duration, Ring, Extension, Number, LineID, AccountID, AccountName, UnitID, UnitName, AreaName, CallType,CallCode, Rate, Cost, TAC,redirected,contactid,CompanyID,CompanyName)
values (#Date, #Duration, #Ring, #Extension, #Number, #LineID, #AccountID, #AccountName, #UnitID, #UnitName, #AreaName, #CallType, #CallCode, #Rate, #Cost, #TAC,1,0,1,'PricewaterhouseCoopers')
end
else if #id>0 and #old_acctid<>#AccountID
update OutboundCalls set AccountID=#AccountID, UnitID=#UnitID,AccountName=#AccountName,UnitName=#UnitName
where OutboundCalls.ID=#id
VB.NET 2015:
Private Sub write_call(c As CallInfo)
Using cnn = New SqlClient.SqlConnection(connString)
Using cmd = New SqlClient.SqlCommand("write_call", cnn)
cmd.Parameters.AddWithValue("#Date", c.dt)
cmd.Parameters.AddWithValue("#Duration", c.secDurn)
cmd.Parameters.AddWithValue("#Ring", 0)
cmd.Parameters.AddWithValue("#Extension", c.src)
cmd.Parameters.AddWithValue("#Number", c.dst)
cmd.Parameters.AddWithValue("#LineID", c.lineId)
cmd.Parameters.AddWithValue("#AccountID", c.account_id)
cmd.Parameters.AddWithValue("#AccountName", c.account_name)
cmd.Parameters.AddWithValue("#UnitID", c.unit_id)
cmd.Parameters.AddWithValue("#UnitName", c.unit_name)
cmd.Parameters.AddWithValue("#AreaName", c.area?.Name)
cmd.Parameters.AddWithValue("#CallType", c.dst_type)
cmd.Parameters.AddWithValue("#CallCode", c.callcode)
cmd.Parameters.AddWithValue("#Rate", c.rate?.rate)
cmd.Parameters.AddWithValue("#Cost", c.Cost)
cmd.Parameters.AddWithValue("#TAC", c._oC)
cnn.Open()
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
Stop
End Try
End Using
End Using
End Sub
It seems that your code misses to set the CommandType property. This property defaults to CommandType.Text and it is appropriate when you pass a sql string as the CommandText.
If you pass the name of a stored procedure you need to set
cmd.CommandType = CommandType.StoredProcedure
without this setting the behavior of the SqlCommand is unpredictable.
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.