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

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}

Related

How to solve this error of conversion failed?

I am getting this error
Conversion failed when converting the varchar value 'Thowheed' to data type int.
I visited and checked in stack overflow, but I couldn't find answer
I added values in drop down list, once I select and click ok button it has to show me the record from database.
This is my code
string cs = ConfigurationManager.ConnectionStrings["Nibrass_DBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Date as Date,Credit, Debit_From as Received_From, Credit_Amount as amount, Reason From Transaction_Credit where Credit = " + DropDownListSelectAccount.SelectedValue+ " or cast(Debit_From as varchar) = " + DropDownListSelectAccount.SelectedValue + " ORDER BY Date DESC";
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
while(rd.Read())
{
DateTime dt = Convert.ToDateTime(rd[0]);
string receivedFrom = rd[1].ToString();
int amount = Convert.ToInt32(rd[2]);
}
con.Close();
}
My database table definition is
CREATE TABLE [dbo].[Transaction_Credit]
(
[Date] DATE NOT NULL,
[Credit] VARCHAR (50) NOT NULL,
[Debit_From] VARCHAR (50) NOT NULL,
[Reason] VARCHAR (100) NULL,
[Credit_Amount] INT NOT NULL,
[Balance] INT NULL
);
You should not be concatenating your string. This is a bad practice and your code becomes vulnerable to SQL Injection.
You should use parameters instead:
cmd.CommandText = #"
SELECT Date
, Credit
, Debit_From AS Received_From
, Credit_Amount AS Amount
, Reason
FROM Transaction_Credit
WHERE Credit = #DropDownListSelectAccount
OR Debit_From = #DropDownListSelectAccount
ORDER BY Date DESC";
cmd.Parameters.Add("#DropDownListSelectAccount", SqlDbType.VarChar, 50). Value) = DropDownListSelectAccount.SelectedValue;
By the way, you don't need to cast Debit_From as a varchar, since it's already like that in your database.
This is your query:
select Date as Date, Credit, Debit_From as Received_From,
Credit_Amount as amount, Reason
from Transaction_Credit
where Credit = " + DropDownListSelectAccount.SelectedValue+ " or
cast(Debit_From as varchar) = " + DropDownListSelectAccount.SelectedValue + "
order by Date DESC;
The code reading this is:
int amount = Convert.ToInt32(rd[2]);
But the 3rd column is Received_From, not amount. That is probably your problem.
Also, cast(Debit_From as varchar) is very dangerous. When you don't include a length for varchar(), SQL Server inserts a length depending on the context. Just don't do a conversion where you don't need one.

Procedure or function 'userpro' expects parameter '#Username', which was not supplied

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) = '',

Very Strange SqlClient error with SmallDatetime parameter in SQL Server 2014 stored proc

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.

How to run stored procedure query between 2 table & insert data base on reference column?

I've created a simple stored procedure to update my Sample_TAG_NUMBERTEST table but I need it to get an ItemCode from another table PartItem by using both SOLine & SONbr to do the query but I don't know how to write it.
2nd thing I need to do is when my StatusCode column is N001 then my DESC column will automatically insert NEW ORDER data value, for PR002 my DESC column will become Progress.
How can I do that? Thanks in advance.
ALTER PROCEDURE [dbo].[SampleTagNumberUpdate]
#sONbr nvarchar(50) = NULL,
#SOLine nvarchar(50) = NULL,
#SerialNbr nvarchar(50) = NULL,
#StatusCode nvarchar(50) = NULL,
#PackType nvarchar(50) = NULL,
#PalletID nvarchar(50) = NULL,
#PackingListNo nvarchar(50) = NULL,
#ItemCode nvarchar(50) = NULL,
#CrDateTime nvarchar(50) = NULL,
#CrUserID nvarchar(50) = NULL,
#return nvarchar(50) = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT sONbr , SOLine
FROM [SampleSystem].[dbo].[Sample_TAG_NUMBERTEST]
WHERE sONbr = #sONbr AND SOLine = #SOLine)
BEGIN
UPDATE [SampleSystem].[dbo].[Sample_TAG_NUMBERTEST]
SET SerialNbr = #SerialNbr
,StatusCode = #StatusCode
,PackType = #PackType
,PalletID = #PalletID
,PackingListNo = #PackingListNo
,ItemCode = #ItemCode
,LastUpdDateTime = GETDATE()
,LastUpdUserID = #CrUserID
WHERE sONbr = #sONbr AND SOLine = #SOLine
IF ##ERROR <> 0
Set #Return = 'UPDATE FAILED'
ELSE
Set #Return = 'UPDATE SUCCESSFULLY'
END
ELSE
BEGIN
INSERT INTO [SampleSystem].[dbo].[Sample_TAG_NUMBERTEST](SONbr, SOLine, SerialNbr
,StatusCode
,PackType
,PalletID
,PackingListNo
,ItemCode
,CrDateTime
,CrUserID)
VALUES(#sONbr, #SOLine, #SerialNbr, #StatusCode, #PackType
,#PalletID
,#PackingListNo
,#ItemCode
,GETDATE()
,#CrUserID)
IF ##ERROR <> 0
Set #Return = 'INSERT DATA FAILED'
ELSE
Set #Return = 'INSERT DATA SUCCESSFULLY'
END
END
I believe I have provided an example for both questions below:
UPDATE T
SET ItemCode = (SELECT PI.ItemCode FROM PartItem AS PI WHERE PI.SO = #SO AND PI.SO_LINE = #SO_LINE),
DESC = CASE #StatusCode WHEN 'N001' THEN 'NEW ORDER'
ELSE CASE #StatusCode WHEN 'PR002' THEN 'PROGRESS' ELSE '' END
END,
<other columns here...>
FROM SAMPLE_TAG_NUMBERTEST AS T

SQL server Nvarchar parameters

I Have created an SP to search against many tables in the db based on string sent form ado
the Vb code
Shared ReadOnly Property Connection() As String
Get
Return ConfigurationManager.ConnectionStrings("ConnString").ConnectionString
End Get
End Property
Function GetData(ByVal SearchKey As String) As DataTable
Dim sqlConn As New SqlConnection(Connection)
Dim ds As New DataSet
Dim sqlCmd As New SqlCommand("Search_List")
Dim sqlAdapter As New SqlDataAdapter
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.Connection = sqlConn
sqlAdapter.SelectCommand = sqlCmd
sqlCmd.Parameters.Add(New SqlParameter("#SearchKey", SqlDbType.NVarChar, 255, ParameterDirection.Input, True, CByte(0), CByte(0), "SearchKey", DataRowVersion.Default, SearchKey))
sqlCmd.Parameters.Add("RerurnValue", SqlDbType.Int)
sqlCmd.Parameters("RerurnValue").Direction = ParameterDirection.ReturnValue
Try
sqlConn.Open()
sqlAdapter.Fill(ds, "Result")
sqlConn.Close()
Catch ex As Exception
Exit Function
End Try
Return ds.Tables("Result")
End Function
and the SQL SP is :
ALTER PROCEDURE [dbo].[Search_List](
#SearchKey NVARCHAR(200)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Rc bigint
DECLARE #Err bigint
set #SearchKey = '%'+#SearchKey+'%'
CREATE
TABLE
#Temp
(
ID BIGINT,
elementType NVARCHAR(10),
NameAr NVARCHAR(255),
NAmeEn NVARCHAR(255),
DescAr NVARCHAR(MAX),
DescEn NVARCHAR(MAX),
URL NVARCHAR(MAX)
)
INSERT INTO #Temp
SELECT
Id
,'C'
,NameAr
,NameEn
,DescAr
,DescEn
,'Counsel.aspx'
FROM
CMS_Councils
Where
(NameAr like #SearchKey
OR
NameEn Like #SearchKey
OR
DescAr Like #SearchKey
OR
DescEn Like #SearchKey)
AND
isnull(Status,0) = 1
select * from #Temp
end
As you can see I have declared argument in VB as Nvarchr and SQL parameter #SearchKey as Nvarchar also if I send english data in #SearchKey search returns correct data, but if I tried to send arabic string in #SearchKey no results appeared knowing that there is arabic data inside the table
Am I missing something?
What Should I do further than that to allow arabic search?
You can try specifying a collation using the COLLATE keyword:
You'd need to specify arabic afterwards, for instance: COLLATE arabic_ci_as
SELECT
Id
,'C'
,NameAr
,NameEn
,DescAr
,DescEn
,'Counsel.aspx'
FROM
CMS_Councils
Where
(NameAr like #SearchKey
OR
NameEn Like #SearchKey
OR
DescAr Like #SearchKey
OR
DescEn Like #SearchKey)
AND
isnull(Status,0) = 1
COLLATE arabic_ci_as