insert MSSQL more than 8000 characters in a nvarchar(max) field - sql

While using sql 2005, it appears I am unable to insert more than 8000 characters in a nvarchar(max) field.
This is really puzzling. I have tried insert, update and update .write with no luck. I can't insert it completely in the console and in .net the error I consistently get is
The data types text and varchar are incompatible in the add operator.
The insert statement is
insert into tablename (columnname) values (' long text');
Update:
update tablename set columnname='long text'
Everything is always truncated at 8000 characters (the text is 11,000 characters). Running a few tests, I see that
select ##textsize
gives 2147483647
Any ideas what I might be doing wrong here?

Your code truncates the value somewhere. You did not include the entire code, so we cannot guess where it truncates. The usual place is parameter declarations. The correct code should be like this:
SqlCommand cmd = new SqlCommand(
#"insert into table (column) values (#param)", conn, trn);
cmd.Paramaters.Add("#param", SqlDbType.NVarChar, -1);
cmd.Parameters["#param"].Value = myLongVariable;
cmd.ExecuteNonQuery();

using (System.Data.SqlClient.SqlConnection con = new
SqlConnection("YourConnection string"))
{
con.Open();
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
{
string expression = "long text.................................";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your long text Parameter Name ",
SqlDbType.NVarChar).Value = expression;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}

I've just had this issue and eventually tracked it down to the ADO constant I was using in the VBA code that calls the stored procedure. Originally I was adVarChar which gave me the "String data, right truncation" message, but when I swapped this out for adLongVarChar it now works fine

cmd.Paramaters.Add("#param", SqlDbType.NVarChar, -1).Value=parametervaluehere;
where -1 means max length for varchar/nvarchar datatype.

Related

VB.NET Oracle SQL "INSERT INTO" with "RETURNING INTO" gives ORA-00933 Command Not Properly Ended

I need to update some code and as part of this I need to insert a row into a table and obtain the id (primary key) of the row just entered.
Have researched this and I believe I should be using RETURNING INTO and Oracle Parameters. I have used parameters in the past successfully to Insert values.
I have an INSERT statement that runs perfectly from VB.NET, but as soon as I add the text "" RETURNING id INTO :myId" I get ORA-00933 Command Not Properly Ended.
Here is a version of the code.
sql = "INSERT ... RETURNING id INTO :myId"
Connect()
Dim intRecsAffected As Integer = 0
Dim comm As OracleCommand = New OracleCommand(sql, _conn)
Dim param As OracleParameter
param = New OracleParameter()
param.ParameterName = ":myId"
param.OracleDbType = OracleDbType.Int32
param.Direction = ParameterDirection.Output ' Tried ReturnValue
comm.Parameters.Add(param)
intRecsAffected = comm.ExecuteNonQuery()
id = comm.Parameters(":myId").Value
Disconnect()
Any ideas?
I believe that your syntax is incorrect:
sql = "INSERT ... RETURNING id INTO myId"
Example below:
https://oracle-base.com/articles/misc/dml-returning-into-clause
Actually, realised what was going on. I cut my full SQL as it's quite long and there's some sensitive stuff in there.
The INSERT was using a SELECT rather than VALUES to get the values for the fields. That won't work - I am guessing because an INSERT with SELECT can add multiple rows even though in this case it won't.
Have re-written the SQL to use VALUES and the VB.Net code works fine.
Thanks to all who replied.

SqlCommandBuilder With Convert Statement

I have an application that's built in .NET language.
In this application we mainly read/write to the database (SQL Server 2005).
Sometimes (for a single input) I just use the SQL query, for example:
commandText = "INSERT INTO Test_Table (Number) VALUES ('10')";
command = new System.Data.SqlClient.SqlCommand(commandText, connection);
command.ExecuteNonQuery();
If I want to update a bunch of records in my database, I use the SqlCommandBuilder class, as in this example:
adapter = new System.Data.SqlClient.SqlDataAdapter("SELECT * FROM Test_Table WHERE Number = '9'",connection);
commandbuilder = new System.Data.SqlClient.SqlCommandBuilder(adapter);
dataset = new System.Data.DataSet();
adapter.Fill(dataset,"Example");
dataset.Tables["Example"].Rows[0].["Number"] = 10;
adapter.update(dataset,"Example");
These work great. But now, for some reason I need to insert/update datetimes and use the CONVERT function on it.
The single SQL query works great:
t = System.DateTime.Now;
commandText = "INSERT INTO Test_Table (DateTime) VALUES (datetime, 't.toString()', 103)";
command = new System.Data.SqlClient.SqlCommand(commandText, connection);
command.ExecuteNonQuery();
This works without a problem, however I have no idea how to achieve the same thing using my SqlCommandBuilder scripts. I could change everything to single query, but this would take a week.
I have already tried the following, without success:
t = System.DateTime.Now;
adapter = new System.Data.SqlClient.SqlDataAdapter("SELECT * FROM Test_Table WHERE Number = '9'", connection);
commandbuilder = new System.Data.SqlClient.SqlCommandBuilder(adapter);
dataset = new System.Data.DataSet();
adapter.Fill(dataset, "Example");
dataset.Tables["Example"].Rows[0].["DateTime"] = "CONVERT(datetime,'" + t.toString() + "',103);
adapter.update(dataset, "Example");
This line of code is weird:
dataset.Tables["Example"].Rows[0].["DateTime"] = "CONVERT(datetime,'" + t.toString() + "',103);
Does it compile? Specifically, this:
.Rows[0].["DateTime"]
I think it should be:
.Rows[0]["DateTime"]
But regardles of the syntax...I don't think this is the right way to go. The datatable (in the dataset) expects a datetime object (btw, don't name your attributes by their datatype, it causes confusion) and you are providing it with something that is incompatible. Sytem.DateTime.Now returns a DateTime object, then you are concatenating it with string (again, does this compile?) and I assume you expect it to be injected into the INSERT statement?
Since you said that it would take a week to change everything, I assume that you have a lot of similar code to repair.
I see three possible solutions, all require some work:
Create a database trigger
https://msdn.microsoft.com/en-us/library/ms189799.aspx
Add a default value to the DateTime field in the database and remove the DateTime from the select query.
http://www.w3schools.com/sql/sql_default.asp
https://www.youtube.com/watch?v=INfi7jkdXC8
(start watching at around 2:00)
You can write a function that does the actual text replacing but it can get tricky:
dasdas as
private string ChangeDate(string insertQuery)
{
// find the location of the date column
// replace the actual value with the "CONVERT(datetime,'" + actualValue + "',103)"
// return the new value and store it in the sqlcommandbuilder.insertstatement
}
Admittedly, all three require work and are not really "elegant". I would go for option 2, because it seems less work. But I don't know if this solves your problem..

Casting ##IDENTITY to Long (Int32) in an Access SQL query

I want to use this syntax but I cant:
Select (Clng ( ##IDENTITY ) )
Or
Clng ( select ( ##IDENTITY ) )
I want to get last inserted id in current scope and cast it to the Long type..how can I make this in one query?
..
This query worked correctly:
Select ##identity
And give me the last inserted autonumber in current session but I want to cast it to the something else in one query
In the first query , You are converting a value into long while you are retrieving it, which is a valid operation.
When you use second query , when select statement is used, you are getting a record set and not an single value.
You can not apply clng on result set but you can apply on a single value
Updated Code:
Check the sample code below:
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
long ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (long)cmd.ExecuteScalar();
}
}
I just gave the C# version of code as i was not much aware of VB or VB.Net . More over , methodology is the same

sql error - missing a (;) at the end of sql statement

I'm trying to get this bit work but it keep saying that missing a (;) at the end of a SQL statement. Basically, this code will get filename of a picture and insert into photodatabase in fileName column, if the filename already exist then just update = 1.
INSERT INTO photoDB(fileNames)
VALUES('" + Path.GetFileName(fileName) + "')
ON DUPLICATE KEY UPDATE fileNames = 1
The error is message is quite clear. You need a semi-colon at the end of your SQL string (fileNames = 1;.
Here is an example that helps to protect against SQL injection and fixes your semi colon problem.
SqlConnection conn = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "INSERT INTO photoDB (fileNames) VALUES(#fileName) ON DUPLICATE KEY UPDATE fileNames = 1;";
command.Parameters.Add(new SqlParameter("#filename", System.Data.SqlDbType.VarChar).Value = Path.GetFileName(fileName));
command.ExecuteNonQuery();
Second answer (now that the OP has fixed the semi-colon issue).
Is this MySQL? Other databases will not support that ON DUPLICATE KEY syntax.
Your ON DUPLICATE KEY clause sets a TEXT column (fileNames) to an INTEGER value (1). Try putting quotes around the integer value.

ASP.NET 2.0: Cannot Convert VarChar to Int

I have an ASP.Net form, where it grabs a value from a textbox:
<asp:TextBox ID="txtID" runat="server" maxlength=9></asp:TextBox>
The ID HAS to be 9 numbers.
After it grabs it, I want to insert it into a database (SQL Server 2005), so I build a parameterized string,
'The Query
cmd.CommandText = "insert into table (aid) values ('#aid')"
cmd.Connection = conn
'Grab the value
cmd.Parameters.add("#aid", SqlDBType.Int).value = txtID.text
'Execute!
cmd.Connection.Open()
cmd.ExecuteNonQuery
However, it doesn't let me. It keeps giving the following error message:
Conversion failed when converting the varchar value '#aid' to data type int.
So I've tried a variety of things:
cmd.Parameters.add("#aid", SqlDBType.Int).value = 999999999
cmd.Parameters.add("#aid", SqlDBType.Int).value = Convert.ToInt16(txtID.text)
cmd.Parameters.add("#aid", SqlDBType.Int).value = Convert.ToInt32(txtID.text)
cmd.Parameters.add("#aid", SqlDBType.Int).value = Convert.ToInt64(txtID.text)
Nothing works. Inside the database, the type is "int".
Any ideas?
Remove the quotes around #aid in your query, so that it looks like so:
cmd.CommandText = "insert into table (aid) values (#aid)"
Otherwise, you're sending the code mixed messages. Parameters are never enclosed in quotes. They are string literals if they're enclosed in quotes. Additionally, in pure SQL, numbers are not enclosed in quotes, but text values (varchar and the like) are. So, remove the quotes, and the parameter should have no issues being created.
Parameters aren't inserted straight into SQL wholesale. They're plopped in after SQL Server has parsed the query. Therefore, parameters should just be on their own, as they're taken as string literals if they aren't. The parameterization will take care to convert the parameter to the right data type for you. See this post for more on how parameters work behind the scenes.
Your sql query is the problem.
You are trying to do
INSERT INTO TABLE(aid) VALUES('123456789')
You need to drop the quotes and do
INSERT INTO TABLE(aid) VALUES(123456789)