I am inserting a record in DB, I am using inline query, I have to get the generated ID, this is how I am doing this
var query = "INSERT INTO [Users] ([Username],[Password]) VALUES(#username,#pwd) SELECT #ID = SCOPE_IDENTITY()";
OleDbParameter[] queryparam = new OleDbParameter[3];
queryparam[0] = new OleDbParameter("#username", OleDbType.VarChar);
queryparam[0].Value = "username";
queryparam[1] = new OleDbParameter("#pwd", OleDbType.VarChar);
queryparam[1].Value = "123456";
queryparam[2] = new OleDbParameter("#ID", OleDbType.Integer);
queryparam[2].Direction = ParameterDirection.Output;
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = DBConnectionHelper.getConnection();
myCommand.CommandText = query;
myCommand.Parameters.AddRange(queryparam);
adapter.InsertCommand = myCommand;
myCommand.ExecuteNonQuery();
I am getting error:
Must declare the scalar variable "#ID".
Must declare the scalar variable "#username".
I also tried using (int)myCommand.ExecuteScalar() but no luck.
How can I get generated ID in this case?
From OleDbCommand.Parameters:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text1. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
So, for your code your query should be:
INSERT INTO [Users] ([Username],[Password]) VALUES(?,?) SELECT ? = SCOPE_IDENTITY()
1Which is the default, so is what your code is using.
From what I can make out of your question, you have declared a variable called query and written your query inside it. Also, your parameter declaration seems to be correct.
Now the problem might be in this line :
myCommand.CommandText = _query;
The variable is query and here you are using _query. So that is probably why the parameters are not added for that particular query and hence the error. It should be like this :
myCommand.CommandText = query;
Hope this clears.
Instead of Select Use Set #Id=Scope_Identity()
Related
i want to get a value using select then use the value from select in a update statement in the same query.
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = connection;
cmd.CommandText = "Declare #appln_id int;set #appln_id=select APPLN_INST_ID from CP.USR_RQST where RQST_ID=#RI;" +
"Update CP.APPLN_INST set SCRN_SESS_DTA=#SSD where APPLN_INST_ID=#appln_id";
cmd.Parameters.Add("#RI", System.Data.SqlDbType.Int).Value = res.RequestDetails.AssetCollectionRequest.RequestId;
cmd.Parameters.Add("#SSD", System.Data.SqlDbType.NVarChar).Value = somevalue;
cmd.Parameters.Add("#appln_id", System.Data.SqlDbType.Int).Direction = ParameterDirection.Output;
connection.Open();
cmd.ExecuteNonQuery();
}
I am getting a syntax error on the query.
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the keyword 'select'.
You didn’t declared #appln_id variable.
When you trying to assign value to a variable you must first declare it. I didn’t see declare keyword in your query.
For example; you put this to top your query. It means before Set command.
declare #appln_id INT; // int is data type of variable. You should change what you need.
try
update CP.APPLN_INST set SCRN_SESS_DTA=#SSD where APPLN_INST_ID=(select APPLN_INST_ID from CP.USR_RQST where RQST_ID=#RI)
I'm trying to follow best practice (and also remove Visual Studio Code Analysis warnings) by using parameters when dropping a SQL Server index.
Not using parameters works fine:
string tableName = "dbo.TableName";
SqlCommand sqlCommand = new SqlCommand("DROP INDEX Blah ON " + tableName);
sqlCommand.Connection = sqlConnection;
sqlCommand.ExecuteNonQuery();
However, when I try to use a parameter I get an error
Incorrect syntax near '#TableName'.
Code:
string tableName = "dbo.TableName";
SqlCommand sqlCommand = new SqlCommand("DROP INDEX Blah ON #TableName");
sqlCommand.Parameters.Add(new SqlParameter("TableName", tableName));
sqlCommand.Connection = sqlConnection;
sqlCommand.ExecuteNonQuery();
What am I doing wrong?
You are doing nothing wrong. Parameters cannot be used to replace identifiers -- column names/aliases, table names/aliases, schema names, and database names. They also cannot be used to replace function names or operators or keywords.
That is a long list. They can be used to replace constants in the query.
I guess the way to remember this is that the parameterized query can be pre-compiled. In order to compile a query, all object references need to be resolved -- so the values cannot be provided by parameters.
You have already solved the problem by putting the table in the string. You can use quotename() to help protect against injection (see here).
DROP INDEX is a DDL statement, most DDL statements don't accept parameterized values. The best you can do is use dynamically constructed SQL and escape the table name using QUOTENAME
string tableName = "dbo.TableName";
string sql = #"
declare #sql nvarchar(500)
set #sql = N'DROP INDEX Blah ON ' + QUOTENAME(#TableName)
exec sp_executesql #sql
";
SqlCommand sqlCommand = new SqlCommand("");
sqlCommand.Parameters.Add("#TableName", SqlDbType.NVarChar, 50).Value = tableName;
sqlCommand.Connection = sqlConnection;
sqlCommand.ExecuteNonQuery();
I also updated your code to use the more "normal" way to add a parameter, explicitly setting the datatype of the parameter.
I am getting this error in Visual Studio for this part of my code. Why? I do declare #TableName below as FormField.
Must declare the table variable "#TableName".
Code:
using (SqlCommand sqlCmd2 = new SqlCommand())
{
sqlCmd2.Connection = sqlConn2;
sqlCmd2.CommandType = System.Data.CommandType.Text;
sqlCmd2.CommandText = string.Format("SELECT DisplayName AS MyColumn FROM #TableName WHERE EventId = 1 AND Visible = 1");
sqlCmd2.Parameters.Add("#TableName", SqlDbType.NVarChar).Value = "FormField";
sqlCmd2.ExecuteNonQuery();
}
The table name can not be resolved by using parameter. For this purpose you have to prepare your statement when passing to SqlCommand:
string tableName = "FormField";
using (SqlCommand sqlCmd2 = new SqlCommand())
{
sqlCmd2.Connection = sqlConn2;
sqlCmd2.CommandType = System.Data.CommandType.Text;
sqlCmd2.CommandText = string.Format("SELECT DisplayName AS MyColumn FROM {0} WHERE EventId = 1 AND Visible = 1", tableName );
sqlCmd2.ExecuteNonQuery();
}
SqlParameter can only be used for passing parameter. E.g. in insert or update statements. But if you want to do this, be sure tableName can not be changed from outside your source code to prevent from sql injection in any case. Youre maybe able to filter acceptable values before executing any queries.
You cannot specify a table name (or column name or function or operator) as a parameter.
Hence, in your query, #TableName is interpreted as a table variable, rather than a parameter and the table variable is not defined.
Alas, you need to put the table in explicitly, using string operations.
I have a SQL query:
String S = Editor1.Content.ToString();
Response.Write(S);
string sql = "insert into testcase.ishan(nmae,orders) VALUES ('9',#S)";
OdbcCommand cmd = new OdbcCommand(sql, myConn);
cmd.Parameters.AddWithValue("#S", S);
cmd.ExecuteNonQuery();
Error: Column 'orders' cannot be null at System.Data.Odbc.OdbcConnection.HandleError
From the manual:
When CommandType is set to Text, the .NET Framework Data Provider for ODBC does not support passing named parameters to an SQL statement or to a stored procedure called by an OdbcCommand. In either of these cases, use the question mark (?) placeholder. For example:
SELECT * FROM Customers WHERE CustomerID = ?
The order in which OdbcParameter objects are added to the OdbcParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
Use this:
string sql = "insert into testcase.ishan(nmae,orders) VALUES ('9', ?)";
OdbcCommand cmd = new OdbcCommand(sql, myConn);
cmd.Parameters.AddWithValue("you_can_write_anything_here_its_ignored_anyway", S);
cmd.ExecuteNonQuery();
it will be helpful to you
cmd.Parameters.Add("#S", OdbcType.Char, S);
Greetings all,
I have a question. I am trying to build a parametrized query to get me the number of rows from a table in Oracle. Rather simple. However I am an Oracle newbie..
I know in SQL Server you can do something like:
Select #outputVariable = count(*) from sometable where name = #SomeOtherVariable
and then you can set up an Output parameter in the System.Data.SqlClient to get the #outputVariable.
Thinking that one should be able to do this in Oracle as well, I have the following query
Select count(*) into :theCount from sometable where name = :SomeValue
I set up my oracle parameters (using System.Data.OracleClient - yes I know it will be deprecated in .Net 4 - but that's what I am working with for now) as follows
IDbCommand command = new OracleCommand();
command.CommandText = "Select count(*) into :theCount from sometable where name = :SomeValue";
command.CommandType = CommandType.Text;
OracleParameter parameterTheCount = new OracleParameter(":theCount", OracleType.Number);
parameterTheCount .Direction = ParameterDirection.Output;
command.Parameters.Add(parameterTheCount );
OracleParameter parameterSomeValue = new OracleParameter(":SomeValue", OracleType.VarChar, 40);
parameterSomeValue .Direction = ParameterDirection.Input;
parameterSomeValue .Value = "TheValueToLookFor";
command.Parameters.Add(parameterSomeValue );
command.Connection = myconnectionObject;
command.ExecuteNonQuery();
int theCount = (int)parameterTheCount.Value;
At which point I was hoping the count would be in the parameter parameterTheCount that I could readily access.
I keep getting the error ora-01036 which http://ora-01036.ora-code.com tells me to check my binding in the sql statement. Am I messing something up in the SQL statement? Am I missing something simple elsewhere?
I could just use command.ExecuteScaler() as I am only getting one item, and am probably going to end up using that, but at this point, curiosity has got the better of me. What if I had two parameters I wanted back from my query (ie: select max(ColA), min(ColB) into :max, :min.....)
Thanks..
Some versions of the ADO does not need the colon : configuring OracleParameter.
Instead of:
new OracleParameter(":theCount", OracleType.Number);
try
new OracleParameter("theCount", OracleType.Number);
Anyway, I think you have to use the ExecuteScalar() function of the IDbCommand and avoiding use of into (which I'm not sure it's valid on this context). I mean:
IDbCommand command = new OracleCommand();
command.CommandText = "Select count(*) from sometable where name = :SomeValue";
command.CommandType = CommandType.Text;
OracleParameter parameterSomeValue = new OracleParameter("SomeValue", OracleType.VarChar, 40);
parameterSomeValue .Direction = ParameterDirection.Input;
parameterSomeValue .Value = "TheValueToLookFor";
command.Parameters.Add(parameterSomeValue );
command.Connection = myconnectionObject;
int theCount = (int)command.ExecuteScalar();
Disclaimer: The code have not been compiled, and may be have any little error.
Update: If you take a look on the Oracle SELECT syntax, you will see that The SELECT INTO sentence is not recognized. But it's valid in PLSQL syntax as you can see here. You can try one of the following to see if it works (not tested):
command.CommandText = "begin Select count(*) into :someCount from sometable where name = :SomeValue; end;";
I think the problem is that you have a trailing space in the parameter name for parameterTheCount.
Edit
Now remove the colons from the parameter names in the constructor to OracleParameter.