I want to insert some data into SQL table. But while inserting int no matter what I've tried I get error:
System.Data.SqlClient.SqlException: 'Conversion failed when converting
the varchar value '#ID' to data type int.'
I even manually set ID to 1 simply to be 100 % sure it's int but still get that error
String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar)
VALUES ('#ID','#secondvar')";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
int ID = 1;
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#secondvar", tableModel.secondvar);
connection.Open();
int result = cmd.ExecuteNonQuery();
Remove the quotes around the values. The framework handles that already.
VALUES ('#ID','#secondvar')
should be
VALUES (#ID,#secondvar)
ID is an integer so it must not be between '':
Change this line:
String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar)
VALUES ('#ID','#secondvar')";
to this:
String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar)
VALUES (#ID,#secondvar)";
And its better avoid using AddWithValue instead use it like:
String query = "INSERT INTO table(dbo.table.ID, dbo.table.secondvar)
VALUES (#ID,'#secondvar')";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
int ID = 1;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ID;
cmd.Parameters.Add("#secondvar", SqlDbType.VarChar).Value = somevalue;
//rest of the code
}
Related
I would like to get last selected person ID.
string personID = "SELECT PersonID FROM TestDatabase.[dbo].[Persons] where name LIKE 'XYZ%'";
SqlCommand cmd = new SqlCommand(personID, con);
SqlDataReader reader = cmd.ExecuteReader();
var lastSelectedSingleClientPhoneId = reader.GetDecimal(0);
But unfortunately it did not work. I already tried to get int16, int32 and int64. When i use INSERT I can get the ID using the following select:
SELECT SCOPE_IDENTITY();
Insert command below:
string insertPerson = "INSERT INTO TestDatabase.[dbo].[Persons] (firstName,secondName) VALUES (#firstName,#secondName);SELECT SCOPE_IDENTITY();";
SqlCommand cmd = new SqlCommand(insertPerson, con);
cmd.Parameters.AddWithValue("#firstName", txt_firstName.Text);
cmd.Parameters.AddWithValue("#secondName", txt_secondName.Text);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
var lastInsertedPersontId = reader.GetDecimal(0);'
This should return all Persons beginning with 'XYZ' in the Persons database table.
string personID = "SELECT PersonID FROM TestDatabase.[dbo].[Persons] where name LIKE 'XYZ%'";
using(var cmd = new SqlCommand(personID, con))
using (var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
Console.WriteLine(reader.GetValue(0));
}
}
I appreciate you're looking for a type to call GetXXX, but you can easily extend this pseudo-code to determine the appropriate type.
You can try combining the two SQL statements as one CommandText value then use ExecuteScalar to return the last inserted ID
string insertPerson = "INSERT INTO TestDatabase.[dbo].[Persons] (firstName,secondName) VALUES (#firstName,#secondName); SELECT SCOPE_IDENTITY();";
SqlCommand cmd = new SqlCommand(insertPerson, con);
cmd.Parameters.AddWithValue("#firstName", txt_firstName.Text);
cmd.Parameters.AddWithValue("#secondName", txt_secondName.Text);
int personID = (int)cmd.ExecuteScalar();
/// ... convert integer value to a string or do something
You can also try this SQL statement as an alternative:
SELECT TOP 1 PersonID FROM Persons ORDER BY PersonID DESC;
I am trying to insert a record that has decimal place, example: 7654.00 and the data type for this column is numeric(10,12) but I am getting arithmetic overflow error and I know I need to do a conversion first but not sure how..
The column I have the issue with is TotalCost.
Here is what I have:
string FullName = row.Cells[1].Text;
string TotalCost = row.Cells[6].ToString();
using (SqlConnection myCon = new SqlConnection(myConnStr))
{
using (SqlCommand myCmd = new SqlCommand())
{
myCmd.Connection = myCon;
myCmd.CommandType = CommandType.Text;
myCmd.CommandText = #"insert into myTable (FullName, TotalCost)
values(#FullName, #TotalCost)";
myCmd.Parameters.AddWithValue("#FullName", FullName.ToString());
myCmd.Parameters.AddWithValue("#TotalCost", TotalCost)
myCon.Open();
myCmd.ExecuteNonQuery();
myCon.Close();
}
}
AddWithValue is a convenient shortcut to add a parameter, but has serious limitations as explained in these two blog posts
Can We Stop using AddWithValue already?
How Data Access Code Affects Database Performance
In your case, you are passing a string as second argument in the AddWithValue for the parameter #TotalCost and AddWithValue, diligently, pass a string to your database engine resulting in the mentioned error.
You should convert your string to a decimal value (It seems more appropriate to use a decimal for money values) and then add the parameter using a more explict declaration of your datatype
string TotalCost = row.Cells[6].ToString();
decimal cost;
if(!decimal.TryParse(TotalCost, out cost))
// Put here an error message for your user
// "The value cannot be converted to a decimal value"
else
{
using (SqlConnection myCon = new SqlConnection(myConnStr))
using (SqlCommand myCmd = new SqlCommand())
{
myCmd.Connection = myCon;
myCmd.CommandType = CommandType.Text;
myCmd.CommandText = #"insert into myTable (FullName, TotalCost )
values(#FullName, #TotalCost)";
myCmd.Parameters.Add("#FullName", SqlDbType.NVarChar).Value = FullName;
myCmd.Parameters.Add("#TotalCost", SqlDbType.Decimal).Value = cost;
myCon.Open();
myCmd.ExecuteNonQuery();
}
}
Of course you should adapt this code to the actual datatype of your TotalCost column on the datatable
I am trying to get the Id of newly inserted row as below,
INSERT dbo.Users(Username)
OUTPUT inserted.ID
VALUES('my new name');
and when I execute this query in SQL Server 2008, it returns the id. My question is how to store this Id in a variable in asp.net C# to use this value further.
Note: I am not using parametrized query.
use the execuate scalar property for your command
int NewNameId = (int)sqlCommand.ExecuteScalar();
DECLARE #inserted TABLE ( id INT NOT NULL);
INSERT dbo.Users(Username)
OUTPUT inserted.ID INTO #inserted
VALUES('my new name');
SELECT (id)
FROM #inserted
not sure. just check
something like:
try
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = null;
SqlDataReader rdr = null;
conn.Open();
cmd = new SqlCommand(sqlsel, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
var _id = rdr.GetInt(0);
}
conn.Close();
// do something with _id
I have this stored procedure:
Insert into dbo.file_row (file_sub_type) values (#file_sub_type)
DECLARE #result int;
SET #result = SCOPE_IDENTITY()
RETURN #result;
This works fine to return the id in SSMS. However, when I call it from C#, it returns -1.
var connection = GetSqlConnection();
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "InsertInto_file_row";
command.Parameters.Add(new SqlParameter("#file_sub_type", fileType));
int result = command.ExecuteNonQuery();
connection.Close();
return result;
I don't see what I am doing wrong. I just need the Id of the inserted record.
Greg
Check the docs on ExecuteNonQuery():
Executes a Transact-SQL statement against the connection and returns the number of rows affected.
(Emphasis mine)
If you want to get information back, you have a couple options:
Change RETURN to SELECT and ExecuteNonQuery() to ExecuteScalar()
Use an OUTPUT parameter
To add on to Joel's response
Try ExecuteScalar instead
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. (Overrides DbCommand.ExecuteScalar().)
This will help you. The function returns the new Identity column value if a new row was inserted, 0 on failure. It is from MSDN
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
public int AddProductCategory(string newName, string connString)
{
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Name", newName);
con.Open();
latestInsertedId = (int)cmd.ExecuteScalar();
con.Close();
}
return latestInsertedId ;
}
}
I want to create a GUID and store it in the DB.
In C# a guid can be created using Guid.NewGuid(). This creates a 128 bit integer. SQL Server has a uniqueidentifier column which holds a huge hexidecimal number.
Is there a good/preferred way to make C# and SQL Server guids play well together? (i.e. create a guid using Guid.New() and then store it in the database using nvarchar or some other field ... or create some hexidecimal number of the form that SQL Server is expecting by some other means)
Here's a code snippet showing how to insert a GUID using a parameterised query:
using(SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using(SqlTransaction trans = conn.BeginTransaction())
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.Transaction = trans;
cmd.CommandText = #"INSERT INTO [MYTABLE] ([GuidValue]) VALUE #guidValue;";
cmd.Parameters.AddWithValue("#guidValue", Guid.NewGuid());
cmd.ExecuteNonQuery();
trans.Commit();
}
}
SQL is expecting the GUID as a string. The following in C# returns a string Sql is expecting.
"'" + Guid.NewGuid().ToString() + "'"
Something like
INSERT INTO TABLE (GuidID) VALUE ('4b5e95a7-745a-462f-ae53-709a8583700a')
is what it should look like in SQL.
You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier.
Your method may look like this (provided that your only parameter is the Guid):
public static void StoreGuid(Guid guid)
{
using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandType = CommandType.StoredProcedure,
CommandText = "StoreGuid",
Parameters = {
new SqlParameter {
ParameterName = "#guid",
SqlDbType = SqlDbType.UniqueIdentifier, // right here
Value = guid
}
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
}
See also: SQL Server's uniqueidentifier
Store it in the database in a field with a data type of uniqueidentifier.
// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(GentEFONRFFConnection);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("your Procedure Name", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("#orgid", SqlDbType.UniqueIdentifier).Value = orgid;
myCommand.Parameters.Add("#statid", SqlDbType.UniqueIdentifier).Value = statid;
myCommand.Parameters.Add("#read", SqlDbType.Bit).Value = read;
myCommand.Parameters.Add("#write", SqlDbType.Bit).Value = write;
// Mark the Command as a SPROC
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConnection.Close();