I want to use join in Oracle 8i. I have my query as below.
I have this query of getting data from two tables using an join, but I get the error SQL command not properly ended.
private List<StamfordProdRelease> GetStamfordProdReleases()
{
List<StamfordProdRelease> list = null;
string srtQry = "SELECT NVL(NULL, 0) ID," +
" DLOG.RELEASEID AS RELEASE_BUILD," +
" TRUNC (DLOGDET.DEPLOYDATE) AS PROD_DEPLOY_DATE," +
" DLOGDET.DEPLOYREQUEST AS BAAR_RFD," +
" DLOG.FILENAMEEXT_VC AS SCRIPT_NAME," +
" DLOG.VERSION," +
" DLOG.REQUEST," +
" DLOG.NOTE AS COMMENTS" +
" FROM ADM_DEPLOYMENTLOGDETAIL DLOGDET" +
" JOIN ADM_DEPLOYMENTLOG DLOG ON DLOG.LOGNO = DLOGDET.LOGNO;";
using (OracleConnection conn = new OracleConnection(Globals.Constants.AppConnectionStringReadOnly))
{
using (OracleCommand objCommand = new OracleCommand(srtQry, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
OracleDataAdapter adp = new OracleDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
list = ConvertToStamfordProdRelease(dt).ToList();
}
}
}
return list;
}
My target is to insert records into a table.
Keep everything in one set of " and also you only need a single ; to end the SQL query outside of the double quotes.
private List<StamfordProdRelease> GetStamfordProdReleases()
{
List<StamfordProdRelease> list = null;
string srtQry = "SELECT NVL(NULL, 0) ID,
DLOG.RELEASEID AS RELEASE_BUILD,
TRUNC (DLOGDET.DEPLOYDATE) AS PROD_DEPLOY_DATE,
DLOGDET.DEPLOYREQUEST AS BAAR_RFD,
DLOG.FILENAMEEXT_VC AS SCRIPT_NAME,
DLOG.VERSION,
DLOG.REQUEST,
DLOG.NOTE AS COMMENTS
FROM ADM_DEPLOYMENTLOGDETAIL DLOGDET
JOIN ADM_DEPLOYMENTLOG DLOG ON DLOG.LOGNO = DLOGDET.LOGNO";
using (OracleConnection conn = new OracleConnection(Globals.Constants.AppConnectionStringReadOnly))
{
using (OracleCommand objCommand = new OracleCommand(srtQry, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
OracleDataAdapter adp = new OracleDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
list = ConvertToStamfordProdRelease(dt).ToList();
}
}
}
return list;
}
Oracle 8i did not support standard ANSI SQL JOIN syntax.
That feature was introduced in Oracle 9i Release 2 (aka Oracle 9.2)
Quote from the chapter "What's New in SQL Reference"
SELECT [...] has new ANSI-compliant join syntax.
Don't combine the, strings put all in one.
Related
This code returns the following error:
"System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'a51'"
a51 is the correct value inside of the record I'm looking for in the EstablishmentCode column of the Establishments table. Account ID is used to find all entries on the Establishments table with that account ID and populate a dataset with Establishment Code values. Account ID value comes from a session variable. Then I use each of these values in a loop where each iteration calls a datareader while loop. Hope I explained this clearly, but I would gladly clarify more if needed. Here's my code.
myConnection.Open();
SqlCommand getEst = new SqlCommand("SELECT EstablishmentCode FROM Establishments WHERE AccountID = " + ID, myConnection);
da = new SqlDataAdapter(getEst);
ds = new DataSet();
da.Fill(ds);
int maxrows = ds.Tables[0].Rows.Count;
for (int x = 0; x < maxrows; x++)
{
getPhones = new SqlCommand("SELECT * FROM DispatcherPhones WHERE EstablishmentCode = " + ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString(), myConnection);
myReader = getPhones.ExecuteReader();
while (myReader.Read())
{
Response.Write("<section id='phone" + myReader["Phone"].ToString() + "' style='padding:20px'>");
Response.Write("<section>Phone Number<br><div class='phone'>" + myReader["Phone"].ToString() + "</div></section>");
Response.Write("<section>Location Code<br><div class='name'>" + myReader["EstablishmentCode"].ToString() + "</div></section>");
Response.Write("<section>Active<br><div class='name'>" + myReader["Active"].ToString() + "</div></section>");
Response.Write("<section class='flex phoneButtonSection'>");
Response.Write("<button type=\"button\" onclick=\"showPhoneForm('" + myReader["ID"].ToString() + "');\">CHANGE</button>");
Response.Write("<button type=\"button\" onclick=\"deletePhones('" + myReader["ID"].ToString() + "');\">DELETE</button>");
Response.Write("</section>");
Response.Write("</section>");
}
myReader.Close();
}
myReader.Close();
myConnection.Close();
String literals in SQL are denoted by single quotes ('s) which are missing for your value:
getPhones = new SqlCommand
("SELECT * " +
"FROM DispatcherPhones
"WHERE EstablishmentCode = '" +
// Here -------------------^
ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString() +
"'" // And here
, myConnection);
Mandatory comment: concatinating strings in order to create SQL statements may leave your code exposed to SQL injection attacks. You should consider using prepared statements instead.
//_whereclause is: where (lastName like '%Davis%')
public static MyList GetAll(string _whereclause)
{
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
string selectSQL = "";
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable]";
if (_whereclause != string.Empty)
{
selectSQL += " #WhereClause";
}
using (SqlCommand myCommand = new SqlCommand(selectSQL, myConnection))
{
myCommand.CommandType = CommandType.Text;
SqlParameter whereClauseParam = new SqlParameter("#WhereClause", SqlDbType.NVarChar, 4000);
whereClauseParam.Value = _whereclause;
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{..............
If I run it with the #WhereClause I get error:
Incorrect syntax near '#WhereClause'.
Your select query should be like
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable] where (lastName like '%" + #WhereClause + "%')";
Assuming that:
SqlParameter whereClauseParam = new SqlParameter("#WhereClause", SqlDbType.NVarChar, 4000);
whereClauseParam.Value = _whereclause; //Here you are getting the value as 'Davis'
But in case you are getting the value in it as where (lastName like '%Davis%') then you simply need to add a space after
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable] ";
^^ here
I try to prevent SQL injection in SQL query. I used following code to do it but unfortunately I faced some problem. The query is not running in oracle DB:
strQuery = #"SELECT PASSWORD FROM IBK_USERS where upper(user_id) =upper(:UserPrefix) AND user_suffix=:UserSufix AND STATUS_CODE='1'";
//strQuery = #"SELECT PASSWORD FROM IBK_CO_USERS where user_id = '" + UserPrefix + "' AND user_suffix='" + UserSufix + "' AND STATUS_CODE='1'";
try
{
ocommand = new OracleCommand();
if (db.GetConnection().State == ConnectionState.Open)
{
ocommand.CommandText = strQuery;
ocommand.Connection = db.GetConnection();
ocommand.Parameters.Add(":UserSufix", OracleDbType.Varchar2,ParameterDirection.Input);
ocommand.Parameters[":UserSufix"].Value = UserSufix;
ocommand.Parameters.Add(":UserPrefix", OracleDbType.Varchar2,ParameterDirection.Input);
ocommand.Parameters[":UserPrefix"].Value = UserPrefix.ToUpper();
odatareader = ocommand.ExecuteReader();
odatareader.Read();
if (odatareader.HasRows)
{
Your parameters shouldn't contain the semicolon :. This is just an indicator in your query that the variable that follows is a parameter, but you don't have to supply that on the .NET side:
ocommand.Parameters["UserSufix"] = ...
When I press insert, I receive the error: Syntax error in INSERT INTO statement
EmployeeID (Autonumber)
EmployeeName(Text)
Position(Text)
Address(Text)
OleDbDataAdapter ad;
DataSet ds;
DataTable dt;
protected void SetInsertParameters()
{
string sql = "INSERT INTO Employee(EmployeeName,Position,Address)"+
" VALUES (#EmployeeName,#Position,#Address)";
ad.InsertCommand = new OleDbCommand(sql, con);
OleDbParameter param = new OleDbParameter("#EmployeeName", OleDbType.VarChar);
param.SourceColumn = "EmployeeName";
param.SourceVersion = DataRowVersion.Current;
ad.InsertCommand.Parameters.Add(param);
param = new OleDbParameter("#Position", OleDbType.VarChar);
param.SourceColumn = "Position";
param.SourceVersion = DataRowVersion.Current;
ad.InsertCommand.Parameters.Add(param);
param = new OleDbParameter("#Address", OleDbType.VarChar);
param.SourceColumn = "Address";
param.SourceVersion = DataRowVersion.Current;
ad.InsertCommand.Parameters.Add(param);
}
void InsertNewValues()
{
dt = ds.Tables["Employee"];
DataRow row = dt.NewRow();
row[0] = txt_employeeID.Text;
row[1] = txt_name.Text;
row[2] = txt_position.Text;
row[3] = txt_address.Text;
dt.Rows.Add(row);
ad.Update(ds, "Employee");
ad.Fill(ds);
}
Position is a reserved word and must be bracketed:
"INSERT INTO Employee(EmployeeName,[Position],Address)"
I have an sql statement that is supposed to return 2 rows. the first with psychological_id = 1, and the second, psychological_id = 2. here is the sql statement
select * from psychological where patient_id = 12 and symptom = 'delire';
But with this code, with which I populate an array list with what is supposed to be 2 different rows, two rows exist, but with the same values: the second row.
OneSymptomClass oneSymp = new OneSymptomClass();
ArrayList oneSympAll = new ArrayList();
string connStrArrayList = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\PatientMonitoringDatabase.mdf; " +
"Initial Catalog=PatientMonitoringDatabase; " +
"Integrated Security=True";
string queryStrArrayList = "select * from psychological where patient_id = " + patientID.patient_id + " and symptom = '" + SymptomComboBoxes[tag].SelectedItem + "';";
using (var conn = new SqlConnection(connStrArrayList))
using (var cmd = new SqlCommand(queryStrArrayList, conn))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
oneSymp.psychological_id = Convert.ToInt32(rdr["psychological_id"]);
oneSymp.patient_history_date_psy = (DateTime)rdr["patient_history_date_psy"];
oneSymp.strength = Convert.ToInt32(rdr["strength"]);
oneSymp.psy_start_date = (DateTime)rdr["psy_start_date"];
oneSymp.psy_end_date = (DateTime)rdr["psy_end_date"];
oneSympAll.Add(oneSymp);
}
}
conn.Close();
}
OneSymptomClass testSymp = oneSympAll[0] as OneSymptomClass;
MessageBox.Show(testSymp.psychological_id.ToString());
the message box outputs "2", while it's supposed to output "1". anyone got an idea what's going on?
You're adding the same instance to the ArrayList twice. Try this:
List<OneSymptomClass> oneSympAll = new List<OneSymptomClass>();
string connStrArrayList =
"Data Source=.\\SQLEXPRESS;" +
"AttachDbFilename=|DataDirectory|\\PatientMonitoringDatabase.mdf; " +
"Initial Catalog=PatientMonitoringDatabase; " +
"Integrated Security=True";
Patient patientID;
string queryStrArrayList =
"select * from psychological where patient_id = " +
patientID.patient_id + " and symptom = '" +
SymptomComboBoxes[tag].SelectedItem + "';";
using (var conn = new SqlConnection(connStrArrayList))
{
using (var cmd = new SqlCommand(queryStrArrayList, conn))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
OneSymptomClass oneSymp = new OneSymptomClass();
oneSymp.psychological_id =
Convert.ToInt32(rdr["psychological_id"]);
oneSymp.patient_history_date_psy =
(DateTime) rdr["patient_history_date_psy"];
oneSymp.strength = Convert.ToInt32(rdr["strength"]);
oneSymp.psy_start_date =
(DateTime) rdr["psy_start_date"];
oneSymp.psy_end_date =
(DateTime) rdr["psy_end_date"];
oneSympAll.Add(oneSymp);
}
}
conn.Close();
}
}
MessageBox.Show(oneSympAll[0].psychological_id.ToString());
MessageBox.Show(oneSympAll[1].psychological_id.ToString());
Note that I replaced the ArrayList with a List<OneSymptomClass>. There is no reason to use ArrayList unless you're using .NET 1.1.
thx for the tip John Saunders. I added a line that makes it work. was that what you were gonna suggest me?
while (rdr.Read())
{
oneSymp = new OneSymptomClass();
oneSymp.psychological_id = Convert.ToInt32(rdr["psychological_id"]);
oneSymp.patient_history_date_psy = (DateTime)rdr["patient_history_date_psy"];
oneSymp.strength = Convert.ToInt32(rdr["strength"]);
oneSymp.psy_start_date = (DateTime)rdr["psy_start_date"];
oneSymp.psy_end_date = (DateTime)rdr["psy_end_date"];
oneSympAll.Add(oneSymp);
}