Implicit casting VARCHAR to VARBINARY is not allowed - c#

I'm stuck with a problem. I'm developing a ASP.net MVC application that manages file uploads to a DB. Not that big of a deal. But every time I execute my SQL-Command, he tells me that I need to convert to VARBINARY first.
That problem is asked a lot here and on the Internet, but I still can't get it working..
That's what I got:
The SQL table:
DocID INT IDENTITY(1,1) NOT NULL,
DocName VARCHAR(512) NOT NULL,
DocData VARBINARY(max) NOT NULL,
ContentType NVARCHAR(100) NOT NULL,
ContentLength BIGINT NOT NULL,
InsertionDate DATETIME NOT NULL DEFAULT GETDATE(),
CONSTRAINT PK_DOC_STORE PRIMARY KEY NONCLUSTERED (DocID)
Read the file to a byte[] with BinaryReader.
var reader = new BinaryReader(file.InputStream);
var data = reader.ReadBytes(file.ContentLength);
And the INSERT INTO C# code:
sqlConnection.Open();
var sqlCommand = new SqlCommand
(
"INSERT INTO DocStore VALUES ('#DocumentName', '#DocumentData', '#DocumentType', '#DocumentSize', '#DocumentDate')"
, sqlConnection
);
sqlCommand.Parameters.AddWithValue("#DocumentName", file.FileName);
sqlCommand.Parameters.AddWithValue("#DocumentData", data);
sqlCommand.Parameters.AddWithValue("#DocumentType", file.ContentType);
sqlCommand.Parameters.AddWithValue("#DocumentSize", file.ContentLength);
sqlCommand.Parameters.AddWithValue("#DocumentDate", DateTime.Now);
var success = sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
What's wrong here? I can't see the problem.. Shouldn't the byte[] work in a parameterized command string like this for the VARBINARY part?

You put quotes around parameter names, which will make them string literals.
Also, I would suggest to specify the columns in the insert statement. If you don't specify the columns to insert on, it takes the exact definition from your table (excluding the ID field since it is auto incremented). It is possible to break your query if you insert a field in between.
INSERT INTO DocStore (DocName, DocData, ContentType, ContentLength, InsertionDate)
VALUES (#DocumentName, #DocumentData, #DocumentType, #DocumentSize, #DocumentDate)

Solution
Instead of
var sqlCommand = new SqlCommand
(
"INSERT INTO DocStore VALUES ('#DocumentName', '#DocumentData', '#DocumentType', '#DocumentSize', '#DocumentDate')"
, sqlConnection
);
I would use
var sqlCommand = new SqlCommand
(
"INSERT INTO DocStore VALUES (#DocumentName, #DocumentData, #DocumentType, #DocumentSize, #DocumentDate)"
, sqlConnection
);
Why ?
Because "INSERT INTO ... '#DocumentData' ... " string contain a T-SQL statement. Within T-SQL, single quotes ('bla') are used to delimit the start and the end of string constant and also, in some cases, it can be used for column delimiters. So '#DocumentData' represents a string / VARCHAR constant from the point of view of SQL Server. In this case, it tries to do an implicit conversion of VARCHAR values ('#D...') to VARBINARY (data type of DocData colum; first column is skipped because it has IDENTITY property). But according to
between VARCHAR and VARBINARY are allowed only explicit conversions.
Note: as a best practice I would explicit define the list of target columns for INSERT statement.

Related

How to solve the "String or binary data would be truncated.\r\nThe statement has been terminated." error?

I have a procedure which updates some records. When I execute it I get the following exception
"String or binary data would be truncated.\r\nThe statement has been terminated."
I could found this occur when the parameter length is larger than variable's length. I checked again changing the size. But didn't work. Go the same exception again. How can I solve this? Please help
Here is my code for update
bool isFinished = dba.update(desingnation, title, initials, surname, fullname, callingName, civilSatatus, natinality, nic, birthday, passport,
hometp, mobiletp, province, district, division, electorate, gramaNiladhari, takafull, p_city,
c_city, p_hno, c_hno, tokens_P, tokens_C, previousEmployeements, bank, branch, type, account, gender, educatinalQ, languageE, languageS, languageT, empNo, appNo);
if (isFinished)
{
WebMsgBox.Show("Successfully Inserted!");
}
else
{
WebMsgBox.Show("Some Errors Occured");
}
}
else
{
WebMsgBox.Show("Some feilds are not valid");
}
}
}
This is the code for passing parameters to stored procedures
try
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandTimeout = 0;
cmd.Transaction = transactions;
/*=======================Update employee details================================*/
cmd.CommandText = "update_HS_HR_EMPLOYEE_AADM";
cmd.Parameters.Add("#appNo", SqlDbType.Int).Value = appNo;
cmd.Parameters.Add("#CALLING_NAME", SqlDbType.VarChar).Value = callingName;
cmd.Parameters.Add("#INITIALS", SqlDbType.VarChar).Value = initials;
cmd.Parameters.Add("#SURNAME", SqlDbType.VarChar).Value = surname;
cmd.Parameters.Add("#TITLE", SqlDbType.VarChar).Value = title;
cmd.Parameters.Add("#NAME", SqlDbType.VarChar).Value = fullname;
cmd.Parameters.Add("#FULLNAME", SqlDbType.VarChar).Value = fullname + " " + surname;
cmd.Parameters.Add("#NIC", SqlDbType.VarChar).Value = nic;
cmd.Parameters.Add("#BDY", SqlDbType.VarChar).Value = birthday;
cmd.Parameters.Add("#GENDER", SqlDbType.VarChar).Value = gender;
cmd.Parameters.Add("#NATIONALITY", SqlDbType.VarChar).Value = natinality;
cmd.Parameters.Add("#CIVILSTATUS", SqlDbType.VarChar).Value = civilSatatus;
cmd.Parameters.Add("#DESIGNATION", SqlDbType.VarChar).Value = desingnation;
cmd.Parameters.Add("#P_ADD1", SqlDbType.VarChar).Value = p_hno;
cmd.Parameters.Add("#P_ADD2", SqlDbType.VarChar).Value = tokens_P[0];
if (tokens_P.Length > 1)
cmd.Parameters.Add("#P_ADD3", SqlDbType.VarChar).Value = tokens_P[1];
else
cmd.Parameters.Add("#P_ADD3", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#P_CITY", SqlDbType.VarChar).Value = p_city;
cmd.Parameters.Add("#TP_HOME", SqlDbType.VarChar).Value = hometp;
cmd.Parameters.Add("#TP_MOBILE", SqlDbType.VarChar).Value = mobiletp;
cmd.Parameters.Add("#PROVINCE", SqlDbType.VarChar).Value = province;
cmd.Parameters.Add("#DISTRICT", SqlDbType.VarChar).Value = district;
cmd.Parameters.Add("#C_ADD1", SqlDbType.VarChar).Value = c_hno;
cmd.Parameters.Add("#C_ADD2", SqlDbType.VarChar).Value = tokens_C[0];
cmd.Parameters.Add("#PER_GNDIV_CODE", SqlDbType.VarChar).Value = gramaNiladhari;
cmd.Parameters.Add("#PER_DSDIV_CODE", SqlDbType.VarChar).Value = division;
cmd.Parameters.Add("#TAKAFUL", SqlDbType.VarChar).Value = takafull;
cmd.Parameters.Add("#PASSPORT_NO", SqlDbType.VarChar).Value = passport;
if (tokens_C.Length > 1)
cmd.Parameters.Add("#C_ADD3", SqlDbType.VarChar).Value = tokens_C[1];
else
cmd.Parameters.Add("#C_ADD3", SqlDbType.VarChar).Value = "";
cmd.Parameters.Add("#C_CITY", SqlDbType.VarChar).Value = c_city;
cmd.Parameters.Add("#ELECTORATE", SqlDbType.VarChar).Value = electorate;
//int appNO = int.Parse((cmd.ExecuteScalar().ToString()));
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
This is the stored procedure
ALTER PROCEDURE [dbo].[update_HS_HR_EMPLOYEE_AADM]
#appNo Int,
#CALLING_NAME VARCHAR(50),
#INITIALS VARCHAR(50),
#SURNAME VARCHAR(50),
#TITLE VARCHAR(50),
#NAME VARCHAR(50),
#FULLNAME VARCHAR(100),
#NIC VARCHAR(15),
#BDY VARCHAR(50),
#GENDER CHAR(1),
#NATIONALITY VARCHAR(50),
#CIVILSTATUS VARCHAR(50),
#DESIGNATION VARCHAR(50),
#P_ADD1 VARCHAR(50),
#P_ADD2 VARCHAR(50),
#P_ADD3 VARCHAR(50),
#P_CITY VARCHAR(50),
#TP_HOME VARCHAR(50),
#TP_MOBILE VARCHAR(50),
#PROVINCE VARCHAR(50),
#DISTRICT VARCHAR(50),
#C_ADD1 VARCHAR(50),
#C_ADD2 VARCHAR(50),
#C_ADD3 VARCHAR(50),
#C_CITY VARCHAR(50),
#ELECTORATE VARCHAR(50),
#PER_GNDIV_CODE VARCHAR(50),
#PER_DSDIV_CODE VARCHAR(50),
#TAKAFUL VARCHAR(50),
#PASSPORT_NO VARCHAR(50)
AS
BEGIN
update [HS_HR_EMPLOYEE_AADM]
SET
[EMP_CALLING_NAME]=#CALLING_NAME
,[EMP_MIDDLE_INI]=#INITIALS
,[EMP_SURNAME]=#SURNAME
,[EMP_TITLE]=#TITLE
,[EMP_NAMES_BY_INI]=#NAME
,[EMP_FULLNAME]=#FULLNAME
,[EMP_NIC_NO]=#NIC
,[EMP_BIRTHDAY]=#BDY
,[EMP_GENDER]=#GENDER
,[NAT_CODE]=#NATIONALITY
,[EMP_MARITAL_STATUS]=#CIVILSTATUS
,[EMP_DATE_JOINED]=GETDATE()
,[EMP_CONFIRM_FLG]=0
,[CT_CODE]='000008'
,[DSG_CODE]=#DESIGNATION
,[CAT_CODE]='000001'
,[EMP_PER_ADDRESS1]=#P_ADD1
,[EMP_PER_ADDRESS2]=#P_ADD2
,[EMP_PER_ADDRESS3]=#P_ADD3
,[EMP_PER_CITY]=#P_CITY
,[EMP_PER_TELEPHONE]=#TP_HOME
,[EMP_PER_MOBILE]=#TP_MOBILE
,[EMP_PER_PROVINCE_CODE]=#PROVINCE
,[EMP_PER_DISTRICT_CODE]=#DISTRICT
,[EMP_TEM_ADDRESS1]=#C_ADD1
,[EMP_TEM_ADDRESS2]=#C_ADD2
,[EMP_PER_ELECTORATE_CODE]=#ELECTORATE
,[EMP_TEM_ADDRESS3]=#C_ADD3
,[EMP_TEM_CITY]=#C_CITY
,[EMP_PER_GNDIV_CODE]=#PER_GNDIV_CODE
,[EMP_PER_DSDIV_CODE]=#PER_DSDIV_CODE
,[EMP_PASSPORT_NO]=#TAKAFUL
,[EMP_TAK]=#PASSPORT_NO
where App_no = #appNo
END
Specify varchar size in SqlDBType.Varchar in C# code matching the size as specified in stored procedure eg.
cmd.Parameters.Add("#CALLING_NAME", SqlDbType.VarChar, 50).Value = callingName;
corresponding to parameter #CALLING_NAME VARCHAR(50) in stored procdeure.
This ensures that size is not exceeded when being passed to stored procedure.
If length is not specified for string parameter , ADO.NET picks up arbitary length value which may exceed the size specified specified in stored procedures VARCHAR parameters.
Also at front end ensure that the number of characters being entered in textboxes doesnot exceed corresponding parameters size.
This can be done using MaxLength attribute or prompting user with message using JQuery/Javascript if size exceeds.
Do it for other parameters and check.
The specified error, "String or binary data would be truncated.\r\nThe statement has been terminated." is showing when you are trying to insert a value that is higher than the specified size of the column, When we look into the given procedure we can't identify the sizes of each column, So it would better if you cross check the sizes of columns with the values that you are giving.
I can say #GENDER may cause a similar issue, since it is defined as #GENDER CHAR(1), in the procedure but you are taking a string to the method and passing as SqlDbType.VarChar instead for that you have to give the value as char. for this particular field
The String or binary data would be truncated error is telling you that you are losing data. One of the annoying things about this error is that it doesn't tell you which column(s) the problem relates to, and in a scenario like this (with lots of columns), it makes it hard to diagnose.
If you have a suitable version of SQL Server (see the following hyperlinked page), you can turn on Trace Flag 460 (this may require a restart) to tell you exactly which table and column the problem relates to.
If not, here's my more manual approach... after which there is some information about how your parameters can be silently truncated without this error (which is not good).
Notice that for each column, there is a value in a C# variable, a declared parameter type (in both the C# code and the stored proc) and the size of the column in the table (the definition of which is missing from the question - which may explain why there isn't an accepted answer yet). All of these maximum lengths and types need to tie up, for all of the columns. You really need to check all of them; but we all like shortcuts, so...
My tip for finding which column(s) are having the problem is to find a scenario where it occurs so that you can easily repeat it - this is particularly easy to do it you have a unit test of this method. Now modify the stored proc to comment out half of the columns, and try again.
If it works, then you know the uncommented columns are fine (for this particular set of data), and the problem was in one of the columns that was commented out, so uncomment half of the lines, and try again.
If it didn't work, then the problem is with the uncommented columns, so comment out half of the remaining columns and try again.
Repeat until you've worked out which columns have problems. I say 'columns', because although it may only be one column having this problem, there could be more than that.
Now put everything back as it was when you started.
Now that you've worked out which column(s) have problems check each column's definition in the table against the stored proc parameter definition, the C# parameter definition, and the value in the C# variable. You may need to track this all the way back to where the value was entered in the user interface, and ensure that suitable restrictions are in place to prevent the value being too big.
As a bonus tip, I like having unit tests that my parameter sizes correspond with the type and size of the column that they relate to. I also have constants representing the max length of each string field and the maximum value of numeric fields. These constants are unit tested against the column in the database, and are used when restricting the values given by the user in the user interface. They can also be used by the unit test of that method, to prove that inserting the largest possible value for each column actually works.
However, note that it is worth making your varchar, nvarchar and varbinary parameters larger than your column sizes due to the silent truncation that occurs with parameter coercion:
​SQL server will silently coerce your values to be whatever​ type the parameter is. For example...
DECLARE #Varchar VARCHAR(8) = 'I will be truncated';
DECLARE #Decimal92 DECIMAL(9,2) = 123.456;
DECLARE #Int INT = 123.456;
SELECT #Varchar, #Decimal92, #Int;
will output...
I will b 123.46 123
This may come as a surprise, given that SQL will complain about something like this:
BEGIN TRANSACTION;
CREATE TABLE tbl_Test(MyColumn NVARCHAR(5) NOT NULL);
INSERT INTO dbo.tbl_Test (MyColumn) VALUES (N'I will be truncated');
ROLLBACK TRANSACTION;
by saying String or binary data would be truncated. And yet the following code does not complain, silently coerces the value and inserts the record:
BEGIN TRANSACTION;
CREATE TABLE tbl_Test(MyColumn NVARCHAR(5) NOT NULL);
DECLARE #MyColumn NVARCHAR(5)=N'I will be truncated'
INSERT INTO dbo.tbl_Test (MyColumn) VALUES (#MyColumn);
ROLLBACK TRANSACTION;
So if you want to be aware of truncation issues occurring, you need to be sure that your parameter has a larger capacity than the column it is going into. For example, if we just change one character...
BEGIN TRANSACTION;
CREATE TABLE tbl_Test(MyColumn NVARCHAR(5) NOT NULL);
DECLARE #MyColumn NVARCHAR(6)=N'I will be truncated'
INSERT INTO dbo.tbl_Test (MyColumn) VALUES (#MyColumn);
ROLLBACK TRANSACTION;
...will give the truncation error. However, notice that this isn't a complete solution because if I try it with a different value...
BEGIN TRANSACTION;
CREATE TABLE tbl_Test(MyColumn NVARCHAR(5) NOT NULL);
DECLARE #MyColumn NVARCHAR(6)=N'Never complain'
INSERT INTO dbo.tbl_Test (MyColumn) VALUES (#MyColumn);
ROLLBACK TRANSACTION;
Then it will silently coerce, truncating after the space, then (because it's a varchar) the value has trailing spaces removed, and it inserts without complaining.
So the only way to be sure is to make your parameter is several characters larger than it needs to be, because there probably won't be multiple spaces in a row. You could use VARCHAR(MAX) for everything, but there is some concern that this could have performance impacts.
One place where this is particularly important is encrypted values. If encrypted values are truncated, then you can't decrypt them. So you need to be sure that your VARBINARY parameters are sized larger than the relevant column so that you would get errors instead of inserting truncated values. In this case, I believe a single character larger is sufficient, since there is no trimming of VARBINARYs. Well, apparently VarBinarys will trim trailing "nul" (ASCII=0) characters from the end; but only if ANSI_PADDING is set to OFF, but as Microsoft say, it should always be set to "ON". This section also covers what trimming occurs with different field types with different settings.
It's also worth saying that SQL isn't even consistent with how it does this. If we re-try the original example with a DECIMAL...
BEGIN TRANSACTION;
CREATE TABLE tbl_Test(MyColumn DECIMAL(9,2) NOT NULL);
INSERT INTO dbo.tbl_Test (MyColumn) VALUES (123.456);
SELECT * FROM tbl_Test
ROLLBACK TRANSACTION;
It doesn't complain about the value having too many decimal places, it just silently coerces it. And the same is true if I do it through a parameter which has more decimal places than the column...
BEGIN TRANSACTION;
CREATE TABLE tbl_Test(MyColumn DECIMAL(9,2) NOT NULL);
DECLARE #MyColumn DECIMAL(9,3)=123.456
SELECT #MyColumn
INSERT INTO dbo.tbl_Test (MyColumn) VALUES (#MyColumn);
SELECT * FROM tbl_Test
ROLLBACK TRANSACTION;
And yet if I give it a value that is too large...
BEGIN TRANSACTION;
CREATE TABLE tbl_Test(MyColumn DECIMAL(9,2) NOT NULL);
INSERT INTO dbo.tbl_Test (MyColumn) VALUES (1234567890.456);
SELECT * FROM tbl_Test
ROLLBACK TRANSACTION;
Then it will complain with Arithmetic overflow error converting numeric to data type numeric. (as it would if I put that value into a parameter first).
One other thing to mention relates to parameter coercion and encryption. Imagine a scenario where you have an SQL column typed DECIMAL(9,2) and a parameter of the same type, and you are giving it a dot net "decimal" from your C# code. If the "decimal" in your code has lots of decimal places, this silent coercion will effectively be asking SQL to do the rounding for you. Which is fine... Until you decide to encrypt that column, because now the value you are encrypting would be a much longer value than the SQL DECIMAL column would have been able to hold, so is probably larger than you have allowed (in terms of your VARBINARY length). In this scenario you would need to ensure the value was rounded to the correct number of decimal places before encryption.
On the trimming trailing space of the parameter. It is only trimming as much as it needs... this shows that it has trimmed one space from the parameter, but left the remaining 4 after the N.
BEGIN TRANSACTION;
CREATE TABLE tbl_Test(MyColumn NVARCHAR(5) NOT NULL);
DECLARE #MyColumn NVARCHAR(6)=N'N complain'
SELECT #MyColumn +'|',LEN(#MyColumn),DATALENGTH(#MyColumn)
INSERT INTO dbo.tbl_Test (MyColumn) VALUES (#MyColumn);
SELECT MyColumn +'|',LEN(MyColumn),DATALENGTH(MyColumn) FROM dbo.tbl_Test
ROLLBACK TRANSACTION;
Yet another learning point about this... the same concept applies to user defined table types which correlate to table definitions.
Here is an example script to demonstrate the issue. Notice that the creation and dropping of the type has to be done outside the transaction.
CREATE TYPE dbo.MyTableType AS TABLE (MyColumn NVARCHAR(5) NOT NULL);
GO
BEGIN TRANSACTION;
DECLARE #MyColumn NVARCHAR(5)=N'I will be truncated'
DECLARE #MyTable AS dbo.MyTableType;
INSERT INTO #MyTable (MyColumn) VALUES (#MyColumn);
CREATE TABLE dbo.tbl_Test (MyColumn NVARCHAR(5) NOT NULL);
INSERT INTO dbo.tbl_Test SELECT MyColumn FROM #MyTable;
ROLLBACK TRANSACTION;
GO
DROP TYPE dbo.MyTableType;
I have few suggestions to identify this: (Choose any 1, and then move to other, if issue still exists. Order doesn't matter, which ever Suggestion, you fell easy).
Suggestion 1: Open the sql profiler and track the requests. Get the query from profiler and run it directly on SQL Server. you may get more details of error.
Steps:
Start debugging, and stop just before you are going to call the db.
Open Profiler, connect to DB.
Click on Clear Trace Window.
Start the debugging.
Stop the profiler, as soon as you got few requests.
Identify the Query, and run on SQL Server.
Suggestion 2: Try to Insert data using SQL Server management studio.
Steps:
Right click on table -> Click on Script Table as -> Insert To.
Now, compare with your Input, if you are passing correctly.
Suggestion 3: Use this code to get the difference between data length and data passed or directly truncate when passing to DB.
Steps:
Create this Class DbContextExtension.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Data.Context
{
public class DbContextExtension
{
private Dictionary<IProperty, int> _maxLengthMetadataCache;
public void AutoTruncateStringToMaxLength(DbContext db)
{
var entries = db?.ChangeTracker?.Entries();
if (entries == null)
{
return;
}
var maxLengthMetadata = PopulateMaxLengthMetadataCache(db);
foreach (var entry in entries)
{
var propertyValues = entry.CurrentValues.Properties.Where(p => p.ClrType == typeof(string));
foreach (var prop in propertyValues)
{
if (entry.CurrentValues[prop.Name] != null)
{
var stringValue = entry.CurrentValues[prop.Name].ToString();
if (maxLengthMetadata.ContainsKey(prop))
{
var maxLength = maxLengthMetadata[prop];
stringValue = TruncateString(stringValue, maxLength);
}
entry.CurrentValues[prop.Name] = stringValue;
}
}
}
}
private Dictionary<IProperty, int> PopulateMaxLengthMetadataCache(DbContext db)
{
_maxLengthMetadataCache ??= new Dictionary<IProperty, int>();
var entities = db.Model.GetEntityTypes();
foreach (var entityType in entities)
{
foreach (var property in entityType.GetProperties())
{
var annotation = property.GetAnnotations().FirstOrDefault(a => a.Name == "MaxLength");
if (annotation != null)
{
var maxLength = Convert.ToInt32(annotation.Value);
if (maxLength > 0 && !_maxLengthMetadataCache.ContainsKey(property))
{
_maxLengthMetadataCache[property] = maxLength;
}
}
}
}
return _maxLengthMetadataCache;
}
private static string TruncateString(string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}
}
}
Use it like this, before calling your SaveChanges:
public class DocumentRepository : IDocumentRepository
{
private readonly DbContext _context;
public DocumentRepository(DbContext context)
{
_context = context;
}
public async Task CreateDocument(Document obj)
{
//Feel free to make it extension method or use it as DI. To make the example easier, I am creating the object here.
var dbExtensions = new DbContextExtension();
dbExtensions.AutoTruncateStringToMaxLength(_context);
await _context.Documents.AddAsync(obj);
await _context.SaveChangesAsync();
}

Unable to store value NULL in SQL

I am trying to store values in database.
How can I assign value NULL in the database, if it a an int.
Query:
#id varchar(10)
UPDATE [Table] SET
[id] = #id -- id is an int in sql
C# code:
I pass the value:
//dATABASE CONNECTION
db.StoredProcedure = "UpdateProjectValues";
db.Paramater("ID",TB_ID.TEXT); //tb_id.text=""
If it has value then that int will be stored but if I do not have the value, then 0 is getting stored, but i want NULL to be stored.
One solution strictly inside the database is:
UPDATE [Table]
SET [id] = (case when #id <> '' then cast(#id as int) end);
This makes the conversion explicit. However, it is probably better to set up the C# code to pass in an integer value that can take on a NULL value.
I thought I'd provide a few alternatives:
1). Handle the value in your stored procedure. Gordon's CASE statement works but since you are using SQL Server you also have the NULLIF() function which you can use like this:
UPDATE TABLE
SET [id] = NULLIF(#ID, '');
2.) Handle this in the C# code using a ternary operator like:
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UpdateProjectValues";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", string.IsNullOrWhiteSpace(TB_ID.TEXT) ? DBNull.Value : (object)TB_ID.TEXT);
There are other ways also, but these are simple examples.

"There was an error parsing the query. SQL Server CE

I wrote an little app in C# to keep track of customers and jobs but I get an error
"There was an error parsing the query.[Token line number = 1, Token
line offset = 14,Token in error = ']
I'm using a SQL Server CE .sdf database
public static void CreateEmployeeTable(string name)
{
conn.Open();
using (SqlCeCommand cmd = conn.CreateCommand())
{
cmd.CommandText = #"CREATE TABLE `#Name` (
`Id` INT(10) NOT NULL AUTO_INCREMENT,
`Job` VARCHAR(50) NULL,
`Pay` VARCHAR(50) NULL,
`TotalJobs` VARCHAR(50) NULL,
`TotalPay` VARCHAR(50) NULL,
PRIMARY KEY (`Id`)";
cmd.Parameters.AddWithValue("#Name", name);
cmd.ExecuteNonQuery();
}
}
I researched the error a lot and seems this error is pretty vague
You cannot parameterise a CREATE table statement that way.
Simply construct the CommandText string in code using string concatenation (being careful of possible SQL Injection vulnerabilities) and execute it.
You cannot parameterize the table name in your example. I altered your create table SQL to conform to supported data types for SQL CE. Please note that the NVARCHAR statements are set to a length of 100 to support up to the 50 characters you were specifying (VARCHAR is not supported).
I tested this code sample, but there are a couple more things to think about:
Your method is currently public. I don't know the context in which you are calling this, but consider making it private or internal.
Consider querying first to determine whether the table already exists to avoid an exception.
If at all possible I would create the connection in a using block directly above your command creation. That way you will know the connection gets closed and disposed. I'll leave that to your discretion.
public static void CreateEmployeeTable(string name)
{
const string createTableFormat = #"CREATE TABLE [{0}] (
Id INT IDENTITY NOT NULL PRIMARY KEY,
Job NVARCHAR(100) NULL,
Pay NVARCHAR(100) NULL,
TotalJobs NVARCHAR(100) NULL,
TotalPay NVARCHAR(100) NULL)";
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
// Just replace with your connection string.
using (SqlCeConnection cn = new SqlCeConnection(Settings.Default.LocalDbConnectionString))
using (SqlCeCommand cmd = cn.CreateCommand())
{
cmd.CommandText = string.Format(createTableFormat, name);
cn.Open();
cmd.ExecuteNonQuery()
}
}

Error converting data type varchar to bigint (C# ASP.NET)

I'm trying to store a Int64 variable to data column with bigint data type. Following is my sql insert query and parameter declarations.
cmd.CommandText = "INSERT INTO tbl_subscribers VALUES ('#callerID2', '#timeStamp', '#unregisterDate ', '1')";
cmd.Parameters.Add("#callerID2", SqlDbType.BigInt);
cmd.Parameters["#callerID2"].Value = SMSObject.callerID;
cmd.Parameters.Add("#timeStamp", SqlDbType.DateTime);
cmd.Parameters["#timeStamp"].Value = SMSObject.timeStamp.ToString("yyyy-MM-dd HH:mm:ss");
cmd.Parameters.Add("#unregisterDate", DBNull.Value);
cmd.Parameters["#unregisterDate"].Value = DBNull.Value;
When it try to store the data, I get
Error converting data type varchar to bigint.
Any advices?
Change
INSERT INTO tbl_subscribers VALUES ('#callerID2', ...
to
INSERT INTO tbl_subscribers VALUES (#callerID2, ...
In case of parametrized sql query, you don't need to put single quote (') with parameter name.
cmd.CommandText = "INSERT INTO tbl_subscribers
VALUES (#callerID2, #timeStamp, #unregisterDate, '1')";

How to get the generated id from an inserted row using ExecuteScalar?

I know that in Oracle I can get the generated id (or any other column) from an inserted row as an output parameter.
Ex:
insert into foo values('foo','bar') returning id into :myOutputParameter
Is there a way to do the same, but using ExecuteScalar instead of ExecuteNonQuery?
I don't want to use output parameters or stored procedures.
ps: I'm using Oracle, not sql server!!!
If you are on oracle, you have to use ExecuteNonQuery and ResultParameter. There is no way to write this as query.
using (OracleCommand cmd = con.CreateCommand()) {
cmd.CommandText = "insert into foo values('foo','bar') returning id into :myOutputParameter";
cmd.Parameters.Add(new OracleParameter("myOutputParameter", OracleDbType.Decimal), ParameterDirection.ReturnValue);
cmd.ExecuteNonQuery(); // an INSERT is always a Non Query
return Convert.ToDecimal(cmd.Parameters["myOutputParameter"].Value);
}
Oracle uses sequences as for his identity columns, if we may say so.
If you have set a sequence for your table primary key, you also have to write a trigger that will insert the Sequence.NextValue or so into your primary key field.
Assuming that you are already familiar with this concept, simply query your sequence, then you will get your answer. What is very practiced in Oracle is to make yourself a function which will return an INT, then within your function, you perform your INSERT. Assuming that you have setup your trigger correctly, you will then be able to return the value of your sequence by querying it.
Here's an instance:
CREATE TABLE my_table (
id_my_table INT PRIMARY KEY
description VARCHAR2(100) NOT NULL
)
CREATE SEQUENCE my_table_seq
MINVALUE 1
MAXVALUE 1000
START WITH 1
INCREMENT BY 2
CACHE 5;
If you want to manage the auto-increment yourself, here's how:
INSERT INTO my_table (
id_my_table,
description
) VALUES (my_table_seq.NEXTVAL, "Some description");
COMMIT;
On the other hand, if you wish not to care about the PRIMARY KEY increment, you may proceed with a trigger.
CREATE OR REPLACE TRIGGER my_table_insert_trg
BEFORE INSERT ON my_table FOR EACH ROW
BEGIN
SELECT my_table_seq.NEXTVAL INTO :NEW.id_my_table FROM DUAL;
END;
Then, when you're inserting, you simply type the INSERT statement as follows:
INSERT INTO my_table (description) VALUES ("Some other description");
COMMIT;
After an INSERT, I guess you'll want to
SELECT my_table_seq.CURRVAL
or something like this to select the actual value of your sequence.
Here are some links to help:
http://www.orafaq.com/wiki/Sequence
http://www.orafaq.com/wiki/AutoNumber_and_Identity_columns
Hope this helps!
You can use below code.
using (OracleCommand cmd = conn.CreateCommand())
{
cmd.CommandText = #"INSERT INTO my_table(name, address)
VALUES ('Girish','Gurgaon India')
RETURNING my_id INTO :my_id_param";
OracleParameter outputParameter = new OracleParameter("my_id_param", OracleDbType.Decimal);
outputParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outputParameter);
cmd.ExecuteNonQuery();
return Convert.ToDecimal(outputParameter.Value);
}
one possible way if one can add one column named "guid" to the table :
when inserting one record from c#, generate a guid and write it to the guid column.
then perform a select with the generated guid, and you have got the id of inserted record :)
Select t.userid_pk From Crm_User_Info T
Where T.Rowid = (select max(t.rowid) from crm_user_info t)
this will return your required id

Categories

Resources