How to solve this error of conversion failed? - sql

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.

Related

I've tried different ways but still it's throwing an error that cannot convert varchar to int

private void button_submit_Click(object sender, EventArgs e)
{
con = new OleDbConnection("Provider=SQLNCLI11;Data Source=.;Integrated Security=SSPI;Initial Catalog=AdventureWorks2012");
cmd = new OleDbCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "usp_empinfo";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#bid",textBox_BID.Text);
cmd.Parameters.AddWithValue("#job",SqlDbType.VarChar).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("#gender",SqlDbType.VarChar).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("#maritalstatus",SqlDbType.VarChar).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
label_Job.Text =label_Job.Text + "" + cmd.Parameters["#job"].Value.ToString();
label_gender.Text=label_gender.Text + "" + cmd.Parameters["#gender"].Value.ToString();
label_MStatus.Text=label_MStatus.Text + "" + cmd.Parameters["#maritalstatus"].Value.ToString();
}
My stored procedure with input and output parameters:
alter PROC USP_EMPINFO
#bid AS varchar(20),
#job as varchar(20) output,
#gender as varchar(20) output,
#maritalstatus as varchar(20) output
as
begin
select #Job=JobTitle,#Gender=Gender,#maritalstatus=MaritalStatus from humanresources.employee
where BusinessEntityID = #bid
end
I can only assume that BusinessEntityID is an int (maybe even an identifier). In that case, I would define the sproc parameter #bid as that same field type (int, if that's what it is). The sproc definition, then, wouldn't allow a non-int value to be passed in.
Then, change the c# code to
cmd.Parameters.Add("#bid",SqlDbType.Int).Value=int.Parse(textBox_BID.Text.Trim()); //trim because you're passing in a string that might be padded
If it blows up at that line, you'll know that even c# can't convert the value to an int, so you'll need to do extra field validation work.

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 update Columns if value is not NULL

I want to update any columns of table TBL_Log if value entered from C# is not NULL. Here is my stored procedure:
Alter PROCEDURE [dbo].[SP_Update_User]
(#User_id as int,#User_Names as nvarchar(max),#End as char(8),#Start as nvarchar(max) ,#Count as int)
AS
BEGIN
UPDATE [dbo].[TBL_Log]
SET User_Names = #User_Names
,[Start] = #start
,[End] = #End
,[Count] = #Count
where User_id = #User_id
END
I have tried to make this work but have not been successful.
code in class D1:
public static DataSet Update_User(int #User_id, string #User_Names, string #End, string #Start, int #Count)
{
SqlConnection myConnection = new SqlConnection(strConecctionString);
SqlDataAdapter sqlcmd = new SqlDataAdapter("SP_Update_UserData_Bot", myConnection);
sqlcmd.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter parameterID_category_ID = new SqlParameter("#User_id", SqlDbType.Int);
parameterID_category_ID.Value = User_id;
sqlcmd.SelectCommand.Parameters.Add(parameterID_category_ID);
SqlParameter parameterID_Part_ID = new SqlParameter("#User_Names", SqlDbType.Int);
parameterID_Part_ID.Value = User_Names;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Part_ID);
SqlParameter parameterID_Series_ID = new SqlParameter("#End", SqlDbType.Char);
parameterID_Series_ID.Value = End;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Series_ID);
SqlParameter parameterID_Model_ID = new SqlParameter("#start", SqlDbType.NVarChar);
parameterID_Model_ID.Value = start;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Model_ID);
SqlParameter parameterID_Count = new SqlParameter("#Count", SqlDbType.Int);
parameterID_Count.Value = Count;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Count);
sqlcmd.SelectCommand.CommandTimeout = int.MaxValue;
DataSet DS = new DataSet();
sqlcmd.Fill(DS);
return DS;
}
This will update only the values that are not null. If the value is null, the column is updated back to its own value.
UPDATE [dbo].[TBL_Log]
SET User_Names = isnull(#User_Names, User_Names)
, [Start] = isnull(#start, [Start])
, [End] = isnull(#End, [End])
, [Count] = isnull(#Count, [Count])
where User_id = #User_id
You should show your .Net code. Probably the best place to add the check is in .NET and don't call the stored procedure if the value you are worried about is NULL.
Also you must specify which value shouldn't be null, but assuming you meant any of them you can do:
IF (#User_Names IS NULL OR #start IS NULL OR #End IS NULL OR #Count IS NULL OR #User_Id IS NULL)
BEGIN
RETURN
END
That will exit of the stored procedure if any of the parameters is null without updating the table
Given you c# code you can either don't call the stored procedure when a value is null or throw an exception. Also you should consider using DateTime instead of string for date values.
You can do the following in your c# code:
if (#User_Names == null || #End == null || #Start == null)
return;
Or preferably
if (#User_Names == null || #End == null || #Start == null)
throw new ArgumentNullException();
You can even check each parameter individually and pass its name as parameter to the Exception to give a meaningful error message.
Your commented out logic is fine:
UPDATE [dbo].[TBL_Log]
SET User_Names = #User_Names,
[Start] = #start,
[End] = #End,
[Count] = #Count
where User_id = #User_id and
(#User_Names is not null and
#AkharinBazdid is not null and
#Pid_Bazdid IS NOT NULL and
#C_Bazdid IS NOT NULL
);
You can also use IF if you prefer.
Notes:
Don't use SQL keywords and reserved words as column names. The escape characters just get in the way.
If start and end are date/times, then use the appropriate types. Don't use strings.

Is this UPDATE table statement correct in an msdn topic

I have seen this type of UPDATE statement (just like insert statement) in the following msdn topic:
http://msdn.microsoft.com/en-us/library/aa0416cz.aspx#Y2461
UPDATE statement:-
adapter.UpdateCommand = New SqlCommand("UPDATE Customers " &
"(CustomerID, CompanyName) VALUES(#CustomerID, #CompanyName) " & _
"WHERE CustomerID = #oldCustomerID AND CompanyName = " &
"#oldCompanyName", connection)
Is this statement correct or not?
I have tried executing it and it is giving syntax errors.
No, it should be:
UPDATE Customers
SET
CustomerID = #CustomerID,
CompanyName = #CompanyName
WHERE
CustomerID = #oldCustomerID AND
CompanyName = #oldCompanyName
Or to be complete with your sample code, it should be:
adapter.UpdateCommand = New SqlCommand("UPDATE Customers SET CustomerID = #CustomerID, CompanyName = #CompanyName WHERE CustomerID = #oldCustomerID AND CompanyName = #oldCompanyName", connection)
Here is another reference for you and this situation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.updatecommand.aspx
That SQL appears to be correct for an INSERT INTO but not for an UPDATE It should read:
adapter.UpdateCommand = New SqlCommand("UPDATE Customers" & _
" SET CustomerID = #CustomerID, CompanyName = #CompanyName)" & _
" WHERE CustomerID = #oldCustomerID AND CompanyName =" & _
" #oldCompanyName", connection)
That SQL is what one would call paramaterized, so that makes this code (lower in the snippet) very important:
adapter.UpdateCommand.Parameters.Add( _
"#CustomerID", SqlDbType.NChar, 5, "CustomerID")
adapter.UpdateCommand.Parameters.Add( _
"#CompanyName", SqlDbType.NVarChar, 30, "CompanyName")
' Pass the original values to the WHERE clause parameters.
Dim parameter As SqlParameter = dataSet.UpdateCommand.Parameters.Add( _
"#oldCustomerID", SqlDbType.NChar, 5, "CustomerID")
parameter.SourceVersion = DataRowVersion.Original
parameter = adapter.UpdateCommand.Parameters.Add( _
"#oldCompanyName", SqlDbType.NVarChar, 30, "CompanyName")
parameter.SourceVersion = DataRowVersion.Original
As far as I can see the syntax is not valid. The following gives Incorrect syntax near '('.
I suggest changing it as per Dan's answer.
CREATE TABLE Customers
(
CustomerID INT,
CompanyName VARCHAR(10)
)
DECLARE
#CustomerID INT,
#CompanyName VARCHAR(10),
#oldCustomerID INT,
#oldCompanyName VARCHAR(10)
UPDATE Customers (CustomerID, CompanyName)
VALUES(#CustomerID, #CompanyName)
WHERE CustomerID = #oldCustomerID AND CompanyName = #oldCompanyName

SQL Server - Multiple Select with Duplicate Names

I'm trying to grab some data from my SQL database as below;
USE exampleDatabase
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC
The problem is when I read the data I get an error 'Name'.
Dim byWeight As String = sqlReader.GetValue(sqlReader.GetOrdinal("Name"))
Dim byAge As String = sqlReader.GetValue(sqlReader.GetOrdinal("Name"))
How would I read this data as above considering I can't use name twice?
I think you are missing a semi-colon after the first SELECT statement. Here's a sample app I put together (note the semicolon in my sql statement):
var sql = "Select TOP 1 name from sys.columns;"
+ "Select TOP 1 name from sys.objects";
var firstname = string.Empty;
var secondname = string.Empty;
var connString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
using ( var conn = new SqlConnection( connString ) )
{
conn.Open();
using ( var cmd = new SqlCommand( sql, conn ) )
{
var reader = cmd.ExecuteReader();
if ( reader == null )
return;
if ( reader.Read() )
firstname = reader.GetString( reader.GetOrdinal( "Name" ) );
reader.NextResult();
if ( reader.Read() )
secondname = reader.GetString( reader.GetOrdinal( "Name" ) );
}
}
Response.Write( firstname + "<br />" );
Response.Write( secondname + "<br />" );
You can achieve the same goal as the semi-colon by using the "GO keyword like so:
var sql = "Select TOP (1) name from sys.columns GO "
+ "Select TOP (1) name from sys.objects";
You can use the 'as' keyword to rename columns in your results, like so:
SELECT TOP(1) [Name] AS ByWeight FROM [Peeps] ORDER BY [Weight] DESC
hmmm... well you could make it one select statement....
USE exampleDatabase
SELECT W.[Name] AS W_Name, A.[Name] AS A_Name FROM
(SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC) W
JOIN (SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC) A
What if you UNION your SQL together into one result set?
USE exampleDatabase
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Weight] DESC
UNION ALL
SELECT TOP(1) [Name] FROM [Peeps] ORDER BY [Age] DESC