stored procedure inserts truncated value - sql

I have a stored procedure that uses several input parameters and insert them into Sql Database. There is a problem with one parameter, #CustomerId, that is truncated (but not always) when inserted into database.
C#:
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CustomerId", Convert.ToInt32(customerId));
cmd.Connection = sqlConn;
sqlConn.Open();
cmd.ExecuteNonQuery();
sqlConn.Close();
Sql SP:
#CustomerId int
INSERT INTO dbo.tblOffers
(CustomerId)
VALUES
(#CustomerId)
sql table datatype:
CustomerId int not null
Example: 564276117 truncated to 4276117 (but its not happening all the time, and there are values greater than 560000000 that are inserted properly)
What am I doing wrong? Thanks

Try Parameters.Add() method instead of AddWithValue.
cmd.Parameters.Add("#CustomerId",SqlDbType.Int).Value=CustomerID;

Would you please try as below: using ToInt64
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CustomerId", Convert.ToInt64(customerId));
cmd.Connection = sqlConn;
sqlConn.Open();
cmd.ExecuteNonQuery();
sqlConn.Close();

Related

Error using SqlAdapter '{"Must declare the table variable \"#tableName\"."}'

I can't see where i'm going wrong and was wondering if you could help at all?
Just a basic SELECT with a table.
With regards to the error message, i thought i was declaring the #tableName variable in the parameters section?
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT * FROM #tableName",con);
adapter.SelectCommand.Parameters.Add(new SqlParameter
{
ParameterName = "#tableName",
Value = tableName,
SqlDbType = SqlDbType.NVarChar
});
adapter.Fill(databaseList);
You cannot pass table names to SELECT as a parameter. Construct your SQL dynamically, by inserting the properly quoted (escaped) table name in the SQL string.
From clause not be expression so, cant send parameter
Try this
SqlDataAdapter adapter = new SqlDataAdapter(string.Format("Select * From {0}", "yourTableName"), con);

Return Bigint in a stored procedure

I have a stored procedure which has to return a bigint as output. below if the definition.
In the body, I'm inserting a row in a table and returning the identity using ##Identity in #LogID output variable.
Everything works except the return part. I have tried casting, converting, selecting and setting the #LogID to ##identity but no luck.
The stored proc is called by enterprise library's Logging block. I'm using Write method of Logwriter class. This is a standard class provided by Microsoft and we have not modified it. I can't show you the code which calls the procedure as this is a DLL and don't have the source code. Anyway, I'm pretty sure it's not the C# code as I get a SQLException so it is something in the sql. The code below is for brevity and there are lots of other columns which I have removed.They are all provided as input parameters.
I'm sure it's a stupid thing, but I'm somehow missing it.
CREATE PROCEDURE [dbo].[WriteLog]
(
#EventID int,
#Priority int,
#LogId bigint OUTPUT
)
INSERT INTO [Log] (EventID, Priority)
VALUES(#EventID,#Priority)
SET #LogID = ##identity
Go
Stored procedures can only return int. So you will need to use the output parameter.
declare #CapturedLogID bigint;
exec dbo.WriteLog #EventID = 42, #Priority = 1337, #LogID = #CapturedLogID output;
In the above example, after the procedure executes, #CapturedLogID stores the value set within the stored procedure (##identity, which, as others have pointed out, should be changed to scope_identity() immediately).
Edit: From C#, to call the procedure with an out parameter:
using (var cmd = new SqlCommand()) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.WriteLog";
cmd.Parameters.Add("EventID", SqlDbType.Int).Value = 42;
cmd.Parameters.Add("Priority", SqlDbType.Int).Value = 1337;
cmd.Parameters.Add("LogID", SqlDbType.BigInt).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
long logID = (long)cmd.Parameters["LogID"].Value;
}
Note that I've only included the code for setting up and executing the SqlCommand object.

How to return a table from a Stored Procedure?

It is very simple question.
I am trying to return a table from a stored procedure, like
select * from emp where id=#id
I want to return this query result as a table. I have to do this through a stored procedure.
Where is your problem??
For the stored procedure, just create:
CREATE PROCEDURE dbo.ReadEmployees #EmpID INT
AS
SELECT * -- I would *strongly* recommend specifying the columns EXPLICITLY
FROM dbo.Emp
WHERE ID = #EmpID
That's all there is.
From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)
DataTable tblEmployees = new DataTable();
using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("#EmpID", SqlDbType.Int));
_cmd.Parameters["#EmpID"].Value = 42;
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_dap.Fill(tblEmployees);
}
YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();
and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.
It's VERY important to include:
SET NOCOUNT ON;
into SP, In First line,
if you do INSERT in SP, the END SELECT can't return values.
THEN, in vb60 you can:
SET RS = CN.EXECUTE(SQL)
OR:
RS.OPEN CN, RS, SQL
In SQL Server 2008 you can use
http://www.sommarskog.se/share_data.html#tableparam
or else simple and same as common execution
CREATE PROCEDURE OrderSummary #MaxQuantity INT OUTPUT AS
SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord
JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID
SELECT #MaxQuantity = MAX(Quantity) FROM [Order Details]
RETURN (SELECT SUM(Quantity) FROM [Order Details])
GO
I hopes its help to you

vb.net ADO CommandBuilder Insert?

I'm using vb.net 2008 and ADO.NET. When using the ADO CommandBuilder and the Insert Command how can I get the newly created Key? (my Table as an Identity column and this is the key.)
Try your insert command somethign like this
insert into table_name values('first value','second value') set #id = SCOPE_IDENTITY()
And then you can set #id Parameter as below
SqlParameter IDParameter =
new SqlParameter("#id",
SqlDbType.Int);
IDParameter.Direction = ParameterDirection.Output;
insertCommand.Parameters.Add(IDParameter);
Finally you can get the value of id parameter in an int variable
int id = (int)IDParameter.Value;

How to check for errors when running DataAdapter/DataSet SQL query?

This is how I update a table using DataAdapter and DataSet in VB using SQL Server:
sqlStmt = String.Format("INSERT INTO my_table (name, lastname) VALUES ('John', 'Doe')")
ds = New DataSet
da = New SqlDataAdapter(sqlStmt, My.Settings.ConnectionString)
da.Fill(ds)
I know that the Fill method does not make sense in case of an INSERT statement, but I am new to this technology and the above statement does the job and updates the table w/o problems. My question is this: If there was an error (say a duplicate key error) how would I know this in my application? Should I be putting the above code in a try/catch block?
Also, if there is a "proper" method for running INSERT statements using a DataAdapter/DataSet combination that does not use the Fill method, please indicate that as well.
For update statements, you should use the SqlCommand object.
SqlCommand cmd = new SqlCommand( "INSERT INTO my_table (name, lastname) VALUES ('John', 'Doe')", My.Settings.ConnectionString);
cmd.ExectureNonQuery();
However it is recommended that you use parameterized SQL queries, if by any chance you are acquiring the data from the user to reduce the chance of SQL Injection attacks :)
SqlCommand cmd = new SqlCommand( "INSERT INTO my_table (name, lastname) VALUES (#FirstName, #LastName)", My.Settings.ConnectionString);
cmd.Parameters.Add("FirstName", SqlDbType.NVarChar);
cmd.Parameters.Add("LastName", SqlDbType.NVarChar);
cmd.Parameters[0].Value = txtFirstName.Text;
cmd.Parameters[1].Value = txtLastName.Text;
cmd.ExecuteNonQuery();
Answer to your other question:
Yes. If there was a primary key violation, a SQLException will be thrown. You can catch it using a try-catch block and show a message or do whatever appropriate.
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error! " + ex.Message);
}