Very Strange SqlClient error with SmallDatetime parameter in SQL Server 2014 stored proc - vb.net

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.

Related

Error converting data type varchar to numeric in sql server

I have created a stored procedure for Save InvoicePayment. When I tried to execute the stored procedure, I get the below error:
Msg 8114, Level 16, State 5, Procedure USP_SaveInvoicePayment_LKO,
Line 0 [Batch Start Line 118] Error converting data type varchar to
numeric.
ALTER PROC Usp_saveinvoicepayment_lko #RECEIPTNO VARCHAR(500),
#INVOICEID BIGINT,
#PayableAmount NUMERIC(10, 2),
#RECEIPTDT DATE,
#PAYMENTMODE VARCHAR(50),
#TRANREF VARCHAR(500),
#USERID BIGINT,
#CHEQUEDATE DATE,
#isValid INT,
#remark VARCHAR(100),
#InvoiceNo VARCHAR(50),
#PaymentRecieved VARCHAR(20),
#PreviousBalance NUMERIC(10, 2),
#ChequeNumber VARCHAR(20),
#PaymentMonth VARCHAR(20),
#PaymentDate DATE,
#CollectorMobile INT,
#Latitude NUMERIC(10, 2),
#Longitude NUMERIC(10, 2),
#RESPONSECODE INT output,
#RESPONSEMESSAGE VARCHAR(255) output,
#IDRESPONSE VARCHAR(200) output
AS
SET nocount ON
BEGIN
--declare #PRJCD varchar(10),
--#KML GEOMETRY ,
--#rowcount int
BEGIN try
--SELECT #PRJCD=PRJCD FROM PRJMST WHERE ID=#PRJID
IF #RECEIPTNO IS NULL
BEGIN
DECLARE #id_out TABLE
(
id VARCHAR(200)
)
--set #ENTRYDATE=getdate()
-- select
convert(varchar,isnull(max(convert(numeric,substring(receiptno,21,50)))+1,1))
from invoicepayment where invoiceid=#invoiceid
INSERT INTO invoicepayment_lko
(receiptno,
invoiceid,
payableamount,
receiptdt,
paymentmode,
trnreference,
userid,
entrydate,
chequedate,
isvalid,
remark,
invoiceno,
paymentrecieved,
previousbalance,
chequenumber,
paymentmonth,
paymentdate,
collectormobile,
latitude,
longitude)
output inserted.receiptno
INTO #id_out
VALUES ( #INVOICENO + '/REC/'
+ (SELECT CONVERT(VARCHAR, Isnull(
Max(CONVERT(NUMERIC, Substring(
receiptno, 21,
50
)))
+ 1, 1))
FROM invoicepayment_lko
WHERE invoiceid = #invoiceid),
#INVOICEID,
#PayableAmount,
#RECEIPTDT,
#PAYMENTMODE,
#TRANREF,
#USERID,
Getdate(),
#CHEQUEDATE,
#isValid,
#remark,
#InvoiceNo,
#PaymentRecieved,
#PreviousBalance,
#ChequeNumber,
#PaymentMonth,
#PaymentDate,
#CollectorMobile,
#Latitude,
#Longitude)
SELECT #IDRESPONSE = id
FROM #id_out
SELECT Ident_current(id)
FROM invoicepayment_lko
UPDATE invoicedetails
SET balanceamt = balanceamt - #PayableAmount
WHERE id = #INVOICEID
END
ELSE
BEGIN
UPDATE invoicepayment_lko
SET chequedate = #CHEQUEDATE,
invoiceid = #INVOICEID,
payableamount = #PayableAmount,
receiptdt = #RECEIPTDT,
paymentmode = #PAYMENTMODE,
trnreference = #TRANREF,
userid = #USERID,
updatedt = Getdate(),
isvalid = #isValid,
remark = #remark,
invoiceno = #InvoiceNo,
paymentrecieved = #PaymentRecieved,
previousbalance = #PreviousBalance,
chequenumber = #ChequeNumber,
paymentmonth = #PaymentMonth,
paymentdate = #PaymentDate,
collectormobile = #CollectorMobile,
latitude = #Latitude,
longitude = #Longitude
WHERE receiptno = #RECEIPTNO
SET #IDRESPONSE = #RECEIPTNO
END
DECLARE #totalPayment NUMERIC(10, 2)
SELECT #totalPayment = Sum(payableamount)
FROM invoicepayment_lko
WHERE invoiceid = #invoiceid
AND isvalid = 1
SELECT #totalPayment,
#invoiceid
END try
BEGIN catch
SELECT #RESPONSECODE = Error_number(),
#RESPONSEMESSAGE = Error_message();
--set #RESPONSEMESSAGE= #prjid;
SELECT #RESPONSECODE,
#RESPONSEMESSAGE
END catch
IF #RESPONSECODE IS NULL
BEGIN
IF #isValid = 0
BEGIN
SET #RESPONSEMESSAGE = 'Payment marked as Invalid'
END
ELSE
BEGIN
SET #RESPONSEMESSAGE = 'Payment created/Updated
Successfully'
END
SET #RESPONSECODE = 200
END
END
--Execution
DECLARE #RESPONSECODE INT = 20,
#RESPONSEMESSAGE VARCHAR(255) = 'Payment Created',
#IDRESPONSE VARCHAR(200) = 'No Response'
EXEC Usp_saveinvoicepayment_lko
NULL,
123,
'87.09',
'2019-07-11',
'Debit',
'test',
12,
'2019-08-11',
1,
'test',
'LP/0819/0000183',
'yES',
'90.09',
'9875',
'7',
'2019-07-18',
988893739,
'28.09',
'76.09',
#RESPONSECODE out,
#RESPONSEMESSAGE out,
#IDRESPONSE out
Please check your input again. As per the parameters passed in procedure
EXEC Usp_saveinvoicepayment_lko
NULL,
123,
'87.09',
'2019-07-11',
'Debit',
'test',
12,
'2019-08-11',
1,
'test',
'LP/0819/0000183',
'yES',
'90.09',
'9875',
'7',
'2019-07-18',
988893739, --- this is one of the reason for your error as you took this as int, but this value will definitly not convert into int.
'28.09',
'76.09',
#RESPONSECODE out,
#RESPONSEMESSAGE out,
#IDRESPONSE out
If you can see for phone number is taken as int and int is not right data type for your field mobile number, either take BigInt or use varchar
My suggestion for mobile number field.
#CollectorMobile BIGINT or VARCHAR(15)

Same ID for THE Multiple Items in SQL Server in ASP.NET

Please help as I want to insert the same ID into multiple records for the billing application.
The table structure is like below:
CREATE TABLE [dbo].[Service_Billing]
(
[Service_ID] INT IDENTITY (1, 1) NOT NULL,
[BillID] INT NULL,
[BillDate] DATETIME NOT NULL,
[Contrid] NCHAR (10) NULL,
[Description] NVARCHAR (250) NULL,
[Qty] NCHAR (10) NULL,
[Post] NVARCHAR (50) NULL,
[Period] NCHAR (10) NULL,
[Rate] NCHAR (10) NULL,
[Amount] NCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([Service_ID] ASC)
);
The stored procedure looks like this:
CREATE PROCEDURE [dbo].[BillAdd]
#BillDate DATETIME,
#Contrid NCHAR(10),
#Description NVARCHAR(250),
#Qty NCHAR(10),
#Post NVARCHAR(50),
#Period NCHAR(10),
#Rate NCHAR(10),
#Amount NCHAR(10)
AS
DECLARE #ser INT = 0
SET #ser = (SELECT MAX(BillID) FROM Service_Billing) + 1
INSERT INTO Service_Billing(BillID, BillDate, ContrID, Qty, Post, Description, Period, Rate, Amount)
VALUES(#ser, #BillDate, #ContrID, #Qty, #Post, #Description, #Period, #Rate, #Amount)
Insert command is like this:
Using con As New SqlConnection(strConnString)
For i As Integer = 0 To Gridview1.Rows.Count - 1
Dim Qty As DropDownList = DirectCast(Gridview1.Rows(i).FindControl("Qty"), DropDownList)
Dim Post As DropDownList = DirectCast(Gridview1.Rows(i).FindControl("Post"), DropDownList)
Dim Period As TextBox = DirectCast(Gridview1.Rows(i).FindControl("Period"), TextBox)
Dim Rate As TextBox = DirectCast(Gridview1.Rows(i).FindControl("Rate"), TextBox)
Dim Amountttl As TextBox = DirectCast(Gridview1.Rows(i).FindControl("Amount"), TextBox)
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "BillAdd"
cmd.Parameters.AddWithValue("#BillDate", Date.ParseExact(billedate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture))
cmd.Parameters.AddWithValue("#ContrID", aggrmnt.SelectedValue)
cmd.Parameters.AddWithValue("#Qty", Qty.SelectedValue)
cmd.Parameters.AddWithValue("#Post", Post.SelectedItem.Text)
cmd.Parameters.AddWithValue("#Description", NewBill_Description.Text)
cmd.Parameters.AddWithValue("#Period", Period.Text)
cmd.Parameters.AddWithValue("#Rate", Rate.Text)
cmd.Parameters.AddWithValue("#Amount", Amountttl.Text)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
Next
'MsgBox("Bill Processed Sucessfully", vbOKOnly)
End Using
and the output is like image below:
What I wish to do with code id like below {Updated them manually}

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

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?

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.

SQL and ADO.net: Too many arguments specified with output param

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.