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

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

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.

Set variable value 0 if select query returns NULL

I have the code below to get the sum of a column from a table.
dim sumX as new oledbcommand
sumX.commandtext = "Select sum(Xcolumn) from [Xtable] where id = "1234""
sumX.commandtype = commandtype.text
sumX.connection = con
Dim z as oledbdatareader = sumX.executereader
If z.read then
y = z.getvalue(0)
End if
The code above works. I want to know what if the code above does not get any value (null), how can I set the value of y to zero if the query's result is null
Try changing the query to this one:
Select IIf(sum(Xcolumn) Is Null,0,sum(Xcolumn)) from [Xtable] where id = "1234"
or this one:
Select Nz(sum(Xcolumn), 0) from [Xtable] where id = "1234"
There's an IIF function in access, it's better to set to 0 in the query.
See if this helps
I just simplified your code to get more performance.It is very useful to use with aggregate functions like Count() or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources
Dim sumX As New OleDbCommand
sumX.CommandText = "Select sum(Xcolumn) from [Xtable] where id = 1234"
sumX.CommandType = CommandType.Text
sumX.Connection = con
y = IIf(IsDBNull(sumX.ExecuteScalar), 0, sumX.ExecuteScalar)
ExecuteScalar() in SqlCommand Object is used for get a single value from Database after its execution. It executes SQL statements or
Stored Procedure and returned a scalar value on first column of first
row in the Result Set. If the Result Set contains more than one
columns or rows , it takes only the first column of first row, all
other values will ignore. If the Result Set is empty it will return a
Null reference.

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..

SQL : how to use IN keyword with prepared statement for range replacement using Java

String sql = "select * from file_repo_index where id in (?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString (1, toCommaSeparatedList(repoIdList));
ResultSet result = ps.executeQuery();
public static String toCommaSeparatedList(Collection col);
I have to use the query as
select * from file_repo_index where id in ( 1,2,3,4 )
But it gives following error in executeQuery() statement
java.sql.SQLException: Conversion failed when converting the nvarchar value '213304,213305,213307' to data type int.
I can use it like
String sql = "select * from file_repo_index where id in ("+toCommaSeparatedList(repoIdList)+")";
Statement ps = conn.createStatement();
ResultSet result = ps.executeQuery(sql);
But I want to use the PrepareStatment method. How can I do it. ??
You should create your prepare statement placeholders based on your values, for instance:
String sql = "select * from file_repo_index where id in (";
//append ?, in above sql in a loop
//Then prepare statement.
This will involve a bit of extra coding, but i think this is the only way to force using PreparedStatement.
If You want to use IN keyword then inside the brackets you have to put like
('213304','213305','213307')
as seperate variables and dont combine in a single "single quotes the entire values" and also in the select statement
String sql = "select * from file_repo_index where id in ("+toCommaSeparatedList(repoIdList)+")";
Change the double quotes to single and try
('+ toCommaSeparatedList(repoIdList) +')";

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

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.