Error occuring in Select Into Statement - c#

I have the following statement which has a syntax error in the 'From' clause, which has a couple of curly table names. The actual database names are the same as the tables, so they are all seperate.
I open a connection to the SealRegister mdb, which is empty (no tables yet), then ExecuteNonQuery on the statement. This I think should create the table SealRegister in the SealRegister.mdb.
sqlcommand = #"Select ""Plant"" As Geometry, A.Asset_ID, B.RoadID, A.AssetType, B.RoadName, B.SegmentNo, C.AadtCount, C.CommVehCnt " +
#"Into [SealRegister] " +
#"From [C:\AR\Plant\Accounting\2015].ARPlntPA_2015_07-2016_06+10yrs As A " +
#"LEFT OUTER JOIN ([C:\AR\Lines\Accounting\2015].ARLnPA_2015_07-2016_06+10yrs As B " +
#"LEFT OUTER JOIN [C:\AR\Lines\TEMP].ARLnX As C On B.Asset_ID = C.Asset_ID) On A.Parent_ID = B.Asset_ID " +
#"WHERE AssetType = 'Wearing Course'";
What do I need to do to correct the syntax
[EDIT]
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\AR\TEMP\SealRegister.mdb"

This works:
sqlcommand = #"Select ""Plant"" As Geometry, A.Asset_ID, B.RoadID, A.AssetType, B.RoadName, B.SegmentNo, C.AadtCount, C.CommVehCnt " +
#"Into [SealRegister] " +
#"From [C:\AR\Plant\Accounting\2015\ARPlntPA_2015_07-2016_06+10yrs].[ARPlntPA_2015_07-2016_06+10yrs] As A " +
#"LEFT OUTER JOIN ([C:\AR\Lines\Accounting\2015\ARLnPA_2015_07-2016_06+10yrs].[ARLnPA_2015_07-2016_06+10yrs] As B " +
#"LEFT OUTER JOIN [C:\AR\Lines\TEMP].ARLnX As C On B.Asset_ID = C.Asset_ID) On A.Parent_ID = B.Asset_ID " +
#"WHERE AssetType = 'Wearing Course'";

Related

c# SqlDataReader throwing syntax error, but the command runs fine in SQL Server?

I'm getting a syntax error from my SQL command shown in the code below. The error is happening on the ExecuteReader line, saying
Incorrect syntax near the keyword 'JOIN'.'
I have no idea why it's throwing a syntax error, the command works perfectly fine in SQL Server. Here's the code:
private void button1_Click(object sender, EventArgs e)
{
SqlCommand sqlcomViewSmashRoster;
SqlDataReader dataReader;
String strSql, strOutput ="";
strSql = "SELECT Roster.CharacterName, Roster.TotalTournamentsParticiaped, Roster.TotalWins, Roster.TotalLosses, Roster.Championships, Roster.InjuriesCaused, Roster.Injured" +
"FROM Roster" +
"INNER JOIN VideoGames" +
"ON VideoGames.VideoGame_ID = Roster.VideoGame_ID" +
"WHERE roster.VideoGame_ID = 2";
cnn.Open();
sqlcomViewSmashRoster = new SqlCommand(strSql, cnn);
dataReader = sqlcomViewSmashRoster.ExecuteReader();
while (dataReader.Read())
{
strOutput = strOutput + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "\n";
}
cnn.Close();
MessageBox.Show(strOutput);
}
Thanks!
Whitespace. Remember that:
"abc" +
"def"
is "abcdef"
Verbatim string literals are your friend:
strSql = #"
SELECT Roster.CharacterName, Roster.TotalTournamentsParticiaped, Roster.TotalWins,
Roster.TotalLosses, Roster.Championships, Roster.InjuriesCaused, Roster.Injured
FROM Roster
INNER JOIN VideoGames
ON VideoGames.VideoGame_ID = Roster.VideoGame_ID
WHERE roster.VideoGame_ID = 2
";
Not only is this easier to code in the first place, but you can easily copy/paste between SSMS and devenv, without having to add quotes etc.
Add space before " otherwise it will concatenate as single word example
"FROM Roster" +
"INNER JOIN VideoGames" +
will become FROM RosterINNER JOIN VideoGames so add space before " & after "
example
strSql = "SELECT Roster.CharacterName, Roster.TotalTournamentsParticiaped, Roster.TotalWins, Roster.TotalLosses, Roster.Championships, Roster.InjuriesCaused, Roster.Injured " +
" FROM Roster " +
" INNER JOIN VideoGames " +
" ON VideoGames.VideoGame_ID = Roster.VideoGame_ID " +
" WHERE roster.VideoGame_ID = 2 ";

MySqlDataAdapter Update table that uses Inner Join

I'm tring to add the Insert, Update and Delete commands to a MySqlDataAdapter which has the data added to it with the command:
//iec211.4521studenti
string lv_sObsTable = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sStudTable = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti'";
string lv_sObservatiiCommand = "SELECT o.idObservatie, o.idStudent, s.nume, o.observatie, o.lastUpdate FROM " + lv_sObsTable + " o INNER JOIN " + lv_sStudTable + " s USING (idStudent) ORDER BY s.nume ASC";
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
I've serched for an answer and I've found two possible solutions for UPDATE, but both of them give me an error:
string lv_sObsTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sStudTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
//VERSION 1
string lv_sCommand = "UPDATE o SET s.idStudent=#idStudent, o.observatie=#observatie FROM " + lv_sObsTB + " AS o INNER JOIN " + lv_sStudTB + " s ON o.idStudent=s.idStudent ";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
//VERSION 2
string lv_sCommand = "UPDATE " + lv_sObsTB + " SET " + "idStudent=#" + lv_sStudTB + ".idStudent, observatie=#observatie WHERE idObservatie=#idObservatie AND " + lv_sObsTB + ".idStudent IN (SELECT " + lv_sStudTB + ".idStudent FROM " + lv_sStudTB + ")";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#" + lv_sStudTB + ".idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
lv_sqlCommand.Parameters.Add("#idObservatie", MySqlDbType.Int16, 10, "idObservatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
The error message for the first version is : "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM iec211.4521observatii ASS o INNER JOIN iec211.4521studenti s ON o.id' at line 1"
The error message for the second version is:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.4521studenti'.idStudenti, observatie='test' WHERE idObservatie=1 ANDiec211.' at line 1"
I don't know how to use the MySQL commands in combination with MySqlCommand and MySqlDataAdapter.
Until now I've used the following command to obtain data for my table:
string lv_sObservatiiCommand = "SELECT * FROM `" + mv_sDatabase + "`.`" + mv_sGroup + "observatii` ORDER BY idStudent ASC";
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
In combination with MySqlCommandBuilder to get the update command and the parameters that needed to be setted:
lv_sqlCommandBuilder = new MySqlCommandBuilder(mv_dtAdapterObservatii);
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommandBuilder.GetUpdateCommand();
Can someone please explain to me how to correctly add the insert, update and delete commands to a MySqlDataAdapter that contains an INNER JOIN between 2 tables ?
I know that each table must be in a different data adapter, and they are. The "4521studenti" table is inside "mv_dtAdapterStudenti", which is not included in the code above.
Thank you for the help and I hope this won't be considered as a bad post. :)
Okey. I think I've figured it out.
This is the SELECT command for 4521observatii:
string lv_sStudent = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
string lv_sObservatii = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sObservatiiCommand = "SELECT o.idObservatie, o.idStudent, s.nume, o.observatie, o.lastUpdate FROM " + lv_sObservatii + " o INNER JOIN " + lv_sStudent + " s USING (idStudent) ORDER BY s.nume ASC";
// Read data from the server for the current table and add it to the DataSet
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
And this is the code for the UPDATE command, inside a different method:
// `iec211`.`4521observatii`
string lv_sObsTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
// `iec211`.`4521studenti`
string lv_sStudTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
string lv_sSelectStudenti = "(SELECT idStudent FROM " + lv_sStudTB + " WHERE idStudent=#idStudent)";
string lv_sCommand = "UPDATE " + lv_sObsTB + " SET idStudent="+ lv_sSelectStudenti + ", observatie=#observatie WHERE idObservatie=#idObservatie";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
lv_sqlCommand.Parameters.Add("#idObservatie", MySqlDbType.Int16, 10, "idObservatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
mv_dtAdapterObservatii.UpdateCommand.Connection = mv_sqlConnection;
The idea is that when I use INNER JOIN I bring data from two different tables and put them together. When I used the UPDATE command, the program didn't know which table he was using and gived those errors.
So I thought what if I update the values of 4521observatii and for the column that is used as FOREIGN KEY I assign the value from 4521studenti.
I know it's like "Tell me your name so I can tell you your name.", but it worked for me.
I hope this will help others and you have a better and cleaner solution, pleas tell me :)

No value given for one or more required parameters c#

An error appear when i want to execute my SQL statement in C# application, which it's:
No value given for one or more required parameters.
I'm using c# with MS access database.
This is my code:
string string2 = "";
if (radButton2 != null)
{
string2 = " and signaal1.info='" + radButton2.Text + "' ";
}
else
string2 = " and signaal1.info='0' ";
if (radButton3 != null)
{
string2 += " and situation.info='" + radButton3.Text + "' ";
}
OleDbCommand cmd = new OleDbCommand("SELECT actionz.info, relationz.id AS actionz FROM ((((relationz LEFT OUTER JOIN conditions ON relationz.conditions_id = conditions.id) LEFT OUTER JOIN situation ON relationz.situation_id = situation.id) LEFT OUTER JOIN car_type ON relationz.car_id = car_type.id) LEFT OUTER JOIN actionz ON relationz.action_id = actionz.id) LEFT OUTER JOIN signal AS signaal1 ON relationz.signal_id = signaal1.id where car_type.info='" + radButton1.Text + "' " + string2 + " ORDER BY conditions.id ASC", objConn);
//cmd.Parameters.AddWithValue("#car_type", radButton1.Text);
OleDbDataReader dataReader = cmd.ExecuteReader();
Typo:
" ...info='" + radButton1.Text + "' " + string2 + " ORDER BY ..."
should be
" ...info='" + radButton1.Text + string2 + "' ORDER BY ..."
or if you need the space between the values:
" ...info='" + radButton1.Text + " " + string2 + "' ORDER BY ..."
Open to Injection though as mentioned.

Join statement using 2 databases on an sql server will not accept database name as a variable

I am currently trying to use an sql join statement to bring back results needed for my program. When i try to change one of the database names to a variable, it is displaying an exception of "System.Data.SqlClient.SqlException (0X80131904): Incorrect syntax near '.'" Both databases are on the same SQL server. If i use one of the database names in the string, it connects and the statement is executed as intended. This only occurs when i put the database name as a parameter:
using (var command = new SqlCommand("select p.Tablefield, P.TableFeild, es.SynchronousIn, es.SynchronousOut, " +
"es.dddd, es.MessageName, es.MessageDate from database.xxx.xxx es " +
"join #Database.dbo.xxxx p on p.GUID = es.dddd where es.MessageName = #MessageType and " +
"(es.MessageDate >= #date and es.MessageDate < #date)" +
"and es.dddd = #ddddd " +
"order by MessageDate DESC" , connection))
The #Database Parameter is defined afterwards:
command.Parameters.Add("#Database", SqlDbType.NVarChar);
command.Parameters["#Database"].Value = DatabaseName;
Any ideas at all? I know this might not be the best way of doing this, I am pretty new to the SQL aspect of c# and would like to know if this is possible. I have replaced certain fields with XXXX or DDDD as this is a tool i am hoping to write for my company.
You can not pass the database name as a parameter. You can add it using String.Format on the sql command string.
Something like this:
String.Format("select p.Tablefield, P.TableFeild, es.SynchronousIn, es.SynchronousOut, " +
"es.dddd, es.MessageName, es.MessageDate from database.xxx.xxx es " +
"join {0}.dbo.xxxx p on p.GUID = es.dddd where es.MessageName = #MessageType and " +
"(es.MessageDate >= #date and es.MessageDate < #date)" + "and es.dddd = #ddddd " +
"order by MessageDate DESC", DatabaseName);
Check the following:
String.Format("select p.Tablefield, P.TableFeild, es.SynchronousIn, es.SynchronousOut, " +
"es.dddd, es.MessageName, es.MessageDate from database.xxx.xxx es " +
"join {0}.dbo.xxxx p on p.GUID = es.dddd where es.MessageName = #MessageType and " +
"(es.MessageDate >= #date and es.MessageDate < #date)" + "and es.dddd = #ddddd " +
"order by MessageDate DESC", DatabaseName);
You cannot pass the table name as a parameter. You could just insert the table name into the SQL string using string.Format. Something like..
using (var command = new SqlCommand("select p.Tablefield, P.TableFeild, es.SynchronousIn, es.SynchronousOut, " +
"es.dddd, es.MessageName, es.MessageDate from database.xxx.xxx es " +
string.Format("join #{0}.dbo.{1} p on p.GUID = es.dddd where es.MessageName = #MessageType and ",databaseName,tableName) +
"(es.MessageDate >= #date and es.MessageDate < #date)" +
"and es.dddd = #ddddd " +
"order by MessageDate DESC" , connection))
Be sure to check this value for SQL injection if it is in any way manipulated from the user interface.

Is there a LIKE operator that will include NULL values?

I'm using SQL Server 2008, with a C# front end. I'm trying to pass a SQL string from C# to SQL Server, and there are 2 fields in my WHERE statement that sometimes might contain NULL values. I've got this code on my Page Load in the code-behind (this is for a report that will be placed in a datagrid):
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlconnectionStatus = new SqlConnection(str);
string DDL_Value = Convert.ToString(Request.QueryString["DDL_Val"]);
string Val_Value = Convert.ToString(Request.QueryString["Val_Val"]);
string Trk_Value = Convert.ToString(Request.QueryString["Trk_Val"]);
string StDt_Value = Convert.ToString(Request.QueryString["StDt_Val"]);
string EnDt_Value = Convert.ToString(Request.QueryString["EnDt_Val"]);
string BTN_Value;
// Because the date is stored as an INT, you have to request the string and then
// convert it to an INT
string StDT_Vals = Request.QueryString["StDt_Val"].ToString();
string EnDT_Vals = Request.QueryString["EnDt_Val"].ToString();
string sqlquery;
sqlquery = "Select DISTINCT PL.PROC_NM as Agent_Name, CCM.UNIQUE_CLAIM_ID as Unique_ID, CCM.CLAIM_ID as Claim_Number, ";
sqlquery = sqlquery + "CCM.SOCSEC as Employee_Last_Digit, CCM.DATE_IMPORTED as Import_Date, CCM.Orig_Open_Date as Original_Review_Date, ";
sqlquery = sqlquery + "AGL.ACCT_GRP as Account_Name, AL.ACCT_NUM as Account_Number, CCM.CDBBEN as Benefit_Option, CCM.BENEFIT_TYPE1 as Benefit_Type1, ";
sqlquery = sqlquery + "CCM.BENEFIT_TYPE2 as Benefit_Type2, CCM.BENEFIT_TYPE3 as Benefit_Type3, CCM.Cmplt as Review_Validated, CCM.Vldtn_Cmmnts as Validation_Comments, ";
sqlquery = sqlquery + "CCM.Gtkpr_Cmmnts as Gatekeeper_Comments, TS.StatusText as Tracking_Status ";
sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
sqlquery = sqlquery + "LEFT JOIN ACCT_LIST AL ON AL.ACCT_NUM = CCM.CDBACC ";
sqlquery = sqlquery + "LEFT JOIN ACCT_GRP_LIST AGL ON AGL.ACCT_GRP_PK = AL.ACCT_GRP_FK ";
sqlquery = sqlquery + "LEFT JOIN TrackingStatus TS ON TS.StatusCode = CCM.TrackingStatus ";
sqlquery = sqlquery + "WHERE CCM.Spare LIKE '" + DDL_Value + "' AND CCM.Cmplt LIKE '" + Val_Value + "' AND CCM.TrackingStatus IN (" + Trk_Value + ") AND CCM.DATE_IMPORTED >= '" + StDt_Value + "' AND CCM.DATE_IMPORTED <= '" + EnDt_Value + "'";
}
The code is sound, it works perfectly fine if a value is selected for all report parameters. The problem is CCM.Spare and CCM.Cmplt can have specific values chosen from a dropdown, or they can be left blank. If left blank, then they need to pull ALL values, whether they're NULL or not. When I leave one (or both) blank, that's where the SQL fails.
I tried checking for blanks and setting the variable equal to '%', but that obviously isn't working; it will only pick up records where there is a value in the field.
I want to do this with one statement if possible before I go cludging it with some If/Then/Else loops.
Is this possible?
try this, I just included the code for the first criteria.
As recommended above, don't concatenate your parameters; the second option is the best way to do it:
sqlquery = sqlquery +
"WHERE CCM.Spare " + (DDL_Value == null ? "IS NULL" : "LIKE '" + DDL_Value + "'") + " AND ...";
sqlquery = sqlquery +
"WHERE CCM.Spare " + (DDL_Value == null ? "IS NULL" : "LIKE #par1") + " AND ...";
Additionaly to increase the speed of your query you could do:
sqlquery = sqlquery +
"WHERE " + (DDL_Value != null ? "CCM.Spare LIKE #par1 AND " : "") + "...";
this will ignore the whole criteria on CCM.Spare if your parameter is null.
If you want all possible values of CCM.Spare and CCM.Cmplt, you simply need to leave off the predicate. Build a separate query (preferable using parametrized queries, as marc_s points out) that omits the WHERE clause referencing the empty dropdown value.

Categories

Resources