Using string SQL queries - c#

I am getting the following error.
Message = "Incorrect syntax near the keyword 'AS'.\r\nIncorrect syntax near the keyword 'AS'."
I have the following sql string query.
private const string QueryString =
"SELECT DISTINCT "
+ " Person.[PersObjId]"
+ ",Person.[PtObjId]"
+ ",MSN.[PersObjId]"
+ ",MSN.[ExtrnId] AS '" + MSNumber + "'"
+ ",HlthProfMstrV.[RptName] AS '" + ItemName + "'"
+ ",HlthProfMstrV.[ItemStsId] AS '" + ItemId + "'"
+ "FROM [dbt1].[Person]"
+ "join"
+ " ( "
+ " SELECT "
+ " PersIdRptV.PersObjId"
+ " , PersIdRptV.ExtrnId"
+ " FROM"
+ " dbt1.PersIdRptV"
+ " join dbt1.IdIssMstrV on PersIdRptV.IdIssObjId = IdIssMstrV.IdIssObjId"
+ " WHERE"
+ " PersIdRptV.TypeId = 5"
+ " and"
+ " PersIdRptV.StpDate is NULL"
+ " ) AS MSN on dbt1.Person.PersObjId = MSN.PersObjId"
+ "left join dbt1.HlthProfMstrV on Person.PCPHlthProfObjId = HlthProfMstrV.HlthProfObjId"
+ " " + "WHERE" + " "
+ "Person.[ExpressId] =12"
+ " and" + " "
+ "Person.[StnTst] = 'Actv' "
+ " and" + " "
+ "MSN.[ExtrnId] = #MSN ";
I think this error is occuring when I am getting the first join result where I assign the result set to "MSN". I tried taking out the AS from AS MSN and I get another error saying the following:
Message = "Incorrect syntax near the keyword 'MSN'.\r\nIncorrect
syntax near the keyword 'MSN'."
I been looking at this for few hours. I am sure its something simple I am missing. Help appreciated!

You're missing a space between last column alias and From keyword:
+ ",HlthProfMstrV.[ItemStsId] AS '" + ItemId + "'"
+ " FROM [dbt1].[Person]"

Space missing before person and join
+ "FROM [dbt1].[Person]"
+ " join" --> Added space before join

+ "MSN.[ExtrnID] = '" + #MSN + "'"

Related

append column data as header/footers to same textfile using winforms application

I am newbie to c# and I want to send a text file with a header and footer using a sql query.
I have an sql results in datagridview and then saved as text file. but everytime i run this query, i should get an header and footer from the sql query. So I am thinking of creating 2 buttons for headers and footers and when i click these it gets the value from sql to datagridview and it copies to textfile and the same for footer just appending different text to the samefile. I want any suggestions can i do like that.
private void btnGetData_Click(object sender, EventArgs e)
{
this.btnGetData.Enabled = false;
Application.DoEvents();
string stringSql = " SELECT distinct " +
"'" + comboBox6.Text + "' as RecordType" +
" , left([CPC No] +' ',30) " +
" , space(1983) " +
",'" + comboBox6.Text + " 'as RecordType" +
, left(t.t_reference + ' ' ,24 ) as ClaimantReference " +
" , left([Claim Number] +' ',30) " +
" , " + comboBox4.Text + " as CourtCode" +
" ,left(ta_title +' ',30) as Title " +
" ,left(ta_surname +' ',30) as Surname " +
", space(180), bat.PCN_Charge as ClaimAmount " +
",[Court Fee] " +
",[Solictors Fees]" +
", (bat.PCN_Charge + [Court Fee]) as TotalAmount" +
",[POC1]" +
",'" + textBox2.Text + "' as RequestType" +
//",'" + comboBox1.Text + "' as RecordType" +
",'" + textBox3.Text + "' as TotalCourtFee" +
",'" + textBox4.Text + "' as TotalClaimAmount" +
" , space(1966) " +
" FROM tickets t " +
" LEFT OUTER JOIN " +
"( " +
" SELECT ticket_addresses.ta_system_ref, ta_title, ta_othername, ta_surname, ta_house_number, ta_address_1, ta_address_2, " +
" ta_address_3, ta_address_4, ta_post_code, ta_telephone, ta_organisation " +
" FROM ticket_addresses " +
" INNER JOIN " +
" ( " +
" SELECT ticket_addresses.ta_system_ref, MAX(ta_address_code) AS ta_address_code " +
" FROM ticket_addresses " +
" GROUP BY ta_system_ref " +
" ) ad " +
" ON (ticket_addresses.ta_system_ref=ad.ta_system_ref AND ticket_addresses.ta_address_code=ad.ta_address_code) " +
")ta " +
"ON (t.t_number=ta.ta_system_ref) " +
" " +
" Inner JOIN " +
" ticket_hold_record b " +
" ON ( t.t_number = b.thr_system_ref) " +
" " +
"Inner JOIN " +
"Rpt_PCNBalance_ALLTickets bat " +
"ON (t.t_number = bat.t_number) " +
" " +
"Inner JOIN " +
"hold_reasons ch " +
"ON (b.thr_hold_type = ch.hr_code) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[Courtfees] cf " +
" ON (bat.Payments >= cf. [Min ClaimAmount]) and (bat.Payments <= cf.[Max Claim Amount]) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[sites] s " +
" ON (t.t_contract = s.Contract) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[claim info] cc " +
" ON (cc.Code COLLATE DATABASE_DEFAULT = t.t_offence_code COLLATE DATABASE_DEFAULT) " +
" and t.t_reference IN {where} ";
//Generate list of Ticket IDS for SQL Where Clause
string whereClause = "";
string[] tempArray = new string[this.txt.Lines.Length];
tempArray = this.txt.Lines;
if (this.txt.Lines.Length == 0)
{
return;
}
for (int counter = 0; counter <= tempArray.Length-1; counter++)
{
if (tempArray[counter].Trim().Length > 0)
{
whereClause = whereClause + "'" + tempArray[counter] + "'" + ", ";
}
}
whereClause = whereClause.TrimEnd(' ', ',');
whereClause = "(" + whereClause + ")";
stringSql = stringSql.Replace("{where}", whereClause);
myDataset = new DataSet("SQL");
SqlConnection myConn = new SqlConnection();
SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.Text;
myCommand.CommandText = stringSql;
myCommand.Connection = myConn;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(myDataset);
this.dataGridView1.DataSource = myDataset.Tables[0];
for (int counter = 0; counter < myDataset.Tables[0].Columns.Count; counter++)
{
this.dataGridView1.Columns[counter].SortMode = DataGridViewColumnSortMode.NotSortable;
}
this.dataGridView1.Refresh();
myConn.Close(); this.btnGetData.Enabled = true;
this.btnSave.Enabled = true;
Application.DoEvents();
}

SQL C# WPF Query Expanded

I had a query answered here SQL Select All Without Values in Another Table.
I've just been asked to integrate the data from another database. This is what I have at the moment.
string _loanSubcontractor = TableNames.Default.LoansSubcontractors;
string _loanPacific = TableNames.Default.LoansPacific;
string _tools = TableNames.Default.Tools;
string _selectStatement = " SELECT [Tools].[Type], [Tools].[Brand], [Tools].[Serial], [Tools].[Year], [Tools].[Code] ";
string _groupBy = " GROUP BY [Tools].[Type], [Tools].[Brand], [Tools].[Serial], [Tools].[Year], [Tools].[Code], [Tools].[Working] ";
string _searchItems = " ([Tools].Code LIKE #toolSerial OR [Tools].Serial LIKE #toolSerial) AND ([Tools].[Working] = 'True' OR [Tools].[Working] IS NULL) ";
SqlConnection myConnection = new SqlConnection(Connection.Default.ConnectionString);
//Checks the main tool information
myConnection.Open();
SqlCommand getTool = new SqlCommand(
_selectStatement + "FROM [" + _tools + "] LEFT OUTER JOIN [" + _loanSubcontractor + "] ON " +
_tools + ".code = [" + _loanSubcontractor + "].ToolCode FULL JOIN [" + _loanPacific + "] ON " + _tools + ".Code = " +
_loanPacific + ".ToolCode WHERE [" + _loanSubcontractor + "].ToolCode IS NULL AND [" + _loanPacific + "].ToolCode IS NULL AND (" + _searchItems + ")" +
"UNION " +
_selectStatement + " FROM [" + _loanSubcontractor + "] INNER JOIN " + _tools + " ON " + _tools + ".Code = [" + _loanSubcontractor + "].ToolCode " +
"INNER JOIN " + _loanPacific + " ON " + _loanPacific + ".ToolCode = " + _tools + ".Code " + _groupBy +
"HAVING (COUNT(" + _loanSubcontractor + ".ReturnDate) = COUNT(*) OR COUNT(" + _loanPacific + ".ReturnDate) = COUNT(*)) " +
" AND " + _searchItems, myConnection);
getTool.Parameters.Add("#toolSerial", SqlDbType.NVarChar).Value = "%" + toolSerial + "%";
What I have is two loan tables (one for employees and one for subcontractors) because the attribute names are different and the data types are also different. Essentially, I need to check that the tool is working, and the tool is not hired out in either of the loan tables (as shown by the return date being null). There may or may not be a loan in either of the tables.
Also, could someone provide me with a link that shows good formatting techniques for SQL within C#?
i sagest you use linq to SQL . this is a part of ADO.NET and you can use long query with 100 % acres and easy way
msdn.microsoft.com for linq to SQL
LINQ to SQL: .NET Language-Integrated Query for Relational Data
Simple LINQ to SQL in C#

How can you update based on the results of an IF statement in query?

As the question above says, I have an IF clause in my query. Now I want to do an UPDATE based on the results of the IF clause. Any ideas how I can do this?
Here is my code:
string cmdstr = "UPDATE itemsordered i " +
"INNER JOIN" +
"( SELECT itemsOrdered_quantity, itemsOrdered_ID, " +
"CASE WHEN itemsOrdered_quantity = '" + quantityTxtBox.Text + "' THEN 'EQUAL' " +
"WHEN itemsOrdered_quantity < '" + quantityTxtBox.Text + "' THEN 'LESS' " +
"WHEN itemsOrdered_quantity > '" + quantityTxtBox.Text + "' THEN 'MORE' " +
"END AS r " +
"FROM itemsordered " +
") res ON i.itemsOrdered_ID = res.itemsOrdered_ID " +
"INNER JOIN stocksdb s ON s.stock_ID = i.stock_ID " +
"IF (res.r = 'EQUAL') " +
"BEGIN " +
"SET s.stock_quantity = (s.stock_quantity + i.itemsOrdered_quantity), " +
"s.stock_dateUpdated = '" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "', " +
"i.itemsOrdered_status = 'RECEIVED', " +
"i.itemsOrdered_dateReceived = '" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "' " +
"WHERE i.itemsOrdered_ID = '" + idTxtBox.Text + "' " +
"END " +
"IF (res.r = 'LESS') " +
"BEGIN " +
"SET s.stock_quantity = (s.stock_quantity + i.itemsOrdered_quantity), " +
"s.stock_dateUpdated = '" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "', " +
"i.itemsOrdered_quantity = (i.itemsOrdered_quantity - " + quantityTxtBox.Text + "), " +
"i.itemsOrdered_dateReceived = '" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "' " +
"WHERE i.itemsOrdered_ID = '" + idTxtBox.Text + "' " +
"END";
cmd = new MySqlCommand(cmdstr, db.mycon);
cmd.ExecuteNonQuery();
MessageBox.Show("ITEM RESTOCKED!");
It returns an error on the cmd.ExecuteNonQuery() and says there is an error near the firstIF clause.
Instead of the IF ... BEGIN, use the CASE expression. Remove the BEGIN ... IF and have only one SET clause. Something like:
SET s.stock_quantity = CASE
WHEN res.r = 'EQUAL' THEN s.stock_quantity + i.itemsOrdered_quantity
ELSE ...
END,
s.stock_dateUpdated = CASE
WHEN res.r = 'EQUAL' THEN ...
ELSE ...
END,
....
...
I would take the IF blocks out and have 2 different SQL statements.
Put the different IF criteria in the WHERE clause of each query.

WebDAV Date Range query

Im trying to access and extract message from Exchange Server 2003. I need to get them by dates but im having problem with it.
Here's the code lsQuery = "<?xml version=\"1.0\"?>"
+ "<D:searchrequest xmlns:D = \"DAV:\" xmlns:m=\"urn:schemas:httpmail:\">"
+ "<D:sql>SELECT \"urn:schemas:httpmail:hasattachment\", \"DAV:displayname\", "
+ "\"urn:schemas:httpmail:from\", \"urn:schemas:httpmail:subject\", "
+ "\"urn:schemas:httpmail:htmldescription\" FROM \"" + lsRootUri
+ "\" WHERE \"DAV:ishidden\" = false "
+ "AND \"DAV:isfolder\" = false "
+ "AND \"urn:schemas:httpmail:hasattachment\" = true "
+ "AND \"urn:schemas:httpmail:read\" = false "
+ "AND \"urn:schemas:httpmail:date \" \">=\" CAST(\"2009/11/17\" as 'dateTime') "
+ "AND \"urn:schemas:httpmail:date \" \"<=\" CAST(\"2009/11/19\" as 'dateTime') "
+ "</D:sql></D:searchrequest>";
http://msdn.microsoft.com/en-us/library/aa123600%28EXCHG.65%29.aspx

How can you use parameterized statements with DB2 Text Search?

I've tried this:
select * from ourschema.mytable
where contains(mysearchablefield, #searchTerms) = 1;
Where #searchTerms was set to "search terms"
Unfortunately, it only produced an error:
ERROR [42610] [IBM][DB2/NT] SQL0418N A statement contains a use of a parameter marker that is not valid. SQLSTATE=42610
Is there a way to use parameterized queries for text search with DB2? If not, is there a document which describes the syntax in detail for manual (ugh) escaping of the search terms (quotes, etc)?
Instead of #field you need to use "?". Everything is basically the same.
Okay, here is a live code sample.
sqlStmt = "SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
"DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
"EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
"COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 1 AS SORTORDER " +
"FROM QMFILES/NVMASTP " +
"WHERE VCLOSEDATE = 0 AND " +
"DEPT_CODE LIKE #DEPT_CODE1 AND " +
"DIVISION_CODE LIKE #DIVISION_CODE1 AND " +
"COMPLAINT_DATE BETWEEN #FROM_COMPLAINT_DATE1 AND #TO_COMPLAINT_DATE1 " +
statusQry +
"UNION " +
"SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
"DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
"EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
"COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 2 AS SORTORDER " +
"FROM QMFILES/NVMASTP " +
"WHERE VCLOSEDATE <> 0 AND " +
"DEPT_CODE LIKE #DEPT_CODE2 AND " +
"DIVISION_CODE LIKE #DIVISION_CODE2 AND " +
"COMPLAINT_DATE BETWEEN #FROM_COMPLAINT_DATE2 AND #TO_COMPLAINT_DATE2 " +
statusQry +
"ORDER BY DEPT_CODE, DIVISION_CODE, COMPLAINT_CODE, SORTORDER";
iDB2Command cmd = new iDB2Command(sqlStmt, conn);
conn.Open();
cmd.DeriveParameters();
conn.Close();
cmd.Parameters["#DEPT_CODE1"].Value = dept;
cmd.Parameters["#DIVISION_CODE1"].Value = serviceArea;
cmd.Parameters["#DEPT_CODE2"].Value = dept;
cmd.Parameters["#DIVISION_CODE2"].Value = serviceArea;
cmd.Parameters["#FROM_COMPLAINT_DATE1"].Value = Convert.ToDecimal(fromDateString);
cmd.Parameters["#TO_COMPLAINT_DATE1"].Value = Convert.ToDecimal(toDateString);
cmd.Parameters["#FROM_COMPLAINT_DATE2"].Value = Convert.ToDecimal(fromDateString);
cmd.Parameters["#TO_COMPLAINT_DATE2"].Value = Convert.ToDecimal(toDateString);
I hope this helps you out more.

Categories

Resources