SQL Query to C# - c#

I am writing this query that I want to transition into C# but I get an error.
The error:
Incorrect syntax near the keyword 'SELECT'.
Incorrect syntax near 'Products'.
Here is the query I am trying to run.
Select
[ID]
,[ProductTypeID]
,[SeriesID]
,[PartNumber]
,[Title]
,[SEOFriendlyURLTitle]
,[HTMLDescription]
,[HTMLValueAdded]
,[RoHSCompliant]
,[ULCompliant]
,[CECompliant]
,[Series]
,[BUSINESS_UNIT]
,[PACKAGING_TYPE]
,[PACK_QTY]
,[MOQ]
,[ORDER_MULTIPLE]
,[LEAD_TIME_WEEKS]
,[INTERNATIONAL_HARMONIZE_CODE]
,[ECCN_NUMBER]
,[COUNTRY_OF_ORIGIN]
,[IS_PART_STATIC_SENSITIVE]
,[IS_PART_LEAD_PB_FREE]
,[MOISTURE_SENSITIVITY_LEVEL_MSL]
,[REGISTERABLE]
,[TAPE_WIDTH]
,[TAPE_MATERIAL]
,[QtyOnHand]
,[QtyOnSalesOrder]
,[QtyOnBackOrder]
,[ProductLine]
,[Reach138Compliant]
,[ConflictMinerals]
,[WebEnabled]
,[DateAdded]
,[UpdateDate]
,[Reviewed]
,[ReviewedBy]
,[Deleted]
,[Book]
,[CustomSort]
,[ONEK]
,[FIVEK]
,[TENK]
,[TWENTYFIVEK]
,[Fifty]
,[OneHundred]
,[FiveHundred]
FROM Products.Products
Join
(SELECT Products.Prices.ProductID,
Max(IIf(Products.Prices.Code='ONEK',Products.Prices.Price,Null)) AS ONEK,
Max(IIf(Products.Prices.Code='FIVEK',Products.Prices.Price,Null)) AS FIVEK,
Max(IIf(Products.Prices.Code='TENK',Products.Prices.Price,Null)) AS TENK,
Max(IIf(Products.Prices.Code='TWENTYFIVEK',Products.Prices.Price,Null)) AS TWENTYFIVEK,
Max(IIf(Products.Prices.Code='Fifty',Products.Prices.Price,Null)) AS Fifty,
Max(IIf(Products.Prices.Code='OneHundred',Products.Prices.Price,Null)) AS OneHundred,
Max(IIf(Products.Prices.Code='FiveHundred',Products.Prices.Price,Null)) AS FiveHundred
FROM Products.Prices
GROUP BY Products.Prices.ProductID
) As pp
ON Products.Products.ID = pp.ProductID
Here is the query in C#:
y1.CommandText = "Select [ID], [PartNumber], [Book], [HTMLDescription], [HTMLValueAdded], [RoHSCompliant], [ULCompliant],[CECompliant], [Series], [BUSINESS_UNIT], [ONEK], [FIVEK], [TENK], [TWENTYFIVEK]" +
",[Fifty], [OneHundred], [FiveHundred], [PACKAGING_TYPE], [PACK_QTY], [MOQ], [ORDER_MULTIPLE], [LEAD_TIME_WEEKS], [INTERNATIONAL_HARMONIZE_CODE], [ECCN_NUMBER], [COUNTRY_OF_ORIGIN]" +
",[IS_PART_STATIC_SENSITIVE], [IS_PART_LEAD_PB_FREE], [MOISTURE_SENSITIVITY_LEVEL_MSL], [REGISTERABLE], [TAPE_WIDTH], [TAPE_MATERIAL], [Reach138Compliant], [ConflictMinerals], [WebEnabled]" +
"FROM Products.Products" +
"Join" +
"(SELECT Products.Prices.ProductID," +
"Max(IIf(Products.Prices.Code='ONEK',Products.Prices.Price,Null)) AS ONEK," +
"Max(IIf(Products.Prices.Code='FIVEK',Products.Prices.Price,Null)) AS FIVEK," +
"Max(IIf(Products.Prices.Code='TENK',Products.Prices.Price,Null)) AS TENK," +
"Max(IIf(Products.Prices.Code='TWENTYFIVEK',Products.Prices.Price,Null)) AS TWENTYFIVEK," +
"Max(IIf(Products.Prices.Code='Fifty',Products.Prices.Price,Null)) AS Fifty," +
"Max(IIf(Products.Prices.Code='OneHundred',Products.Prices.Price,Null)) AS OneHundred," +
"Max(IIf(Products.Prices.Code='FiveHundred',Products.Prices.Price,Null)) AS FiveHundred" +
"FROM Products.Prices" +
"GROUP BY Products.Prices.ProductID" +
") As pp" +
"ON Products.Products.ID = pp.ProductID" +
"where partnumber like '6%'";
Please help and thank you.

Take this segment as an example:
"FROM Products.Products" +
"Join" +
When these strings are concatenated, you get:
"FROM Products.ProductsJoin"
You need to include the spaces.
"FROM Products.Products " +
"Join" +

You are missing SPACES in front of FROM, Join, (SELECT etc... So when they are being output you are seeing FROM Products.ProductsJoin. You also want to prefix with # to protect against escaping issue. To fix you want:
y1.CommandText = #"Select [ID], [PartNumber], [Book], [HTMLDescription], [HTMLValueAdded], [RoHSCompliant], [ULCompliant],[CECompliant], [Series], [BUSINESS_UNIT], [ONEK], [FIVEK], [TENK], [TWENTYFIVEK]" +
",[Fifty], [OneHundred], [FiveHundred], [PACKAGING_TYPE], [PACK_QTY], [MOQ], [ORDER_MULTIPLE], [LEAD_TIME_WEEKS], [INTERNATIONAL_HARMONIZE_CODE], [ECCN_NUMBER], [COUNTRY_OF_ORIGIN]" +
",[IS_PART_STATIC_SENSITIVE], [IS_PART_LEAD_PB_FREE], [MOISTURE_SENSITIVITY_LEVEL_MSL], [REGISTERABLE], [TAPE_WIDTH], [TAPE_MATERIAL], [Reach138Compliant], [ConflictMinerals], [WebEnabled]" +
" FROM Products.Products" +
" Join" +
" (SELECT Products.Prices.ProductID," +
"Max(IIf(Products.Prices.Code='ONEK',Products.Prices.Price,Null)) AS ONEK," +
"Max(IIf(Products.Prices.Code='FIVEK',Products.Prices.Price,Null)) AS FIVEK," +
"Max(IIf(Products.Prices.Code='TENK',Products.Prices.Price,Null)) AS TENK," +
"Max(IIf(Products.Prices.Code='TWENTYFIVEK',Products.Prices.Price,Null)) AS TWENTYFIVEK," +
"Max(IIf(Products.Prices.Code='Fifty',Products.Prices.Price,Null)) AS Fifty," +
"Max(IIf(Products.Prices.Code='OneHundred',Products.Prices.Price,Null)) AS OneHundred," +
"Max(IIf(Products.Prices.Code='FiveHundred',Products.Prices.Price,Null)) AS FiveHundred" +
" FROM Products.Prices" +
" GROUP BY Products.Prices.ProductID" +
") As pp" +
" ON Products.Products.ID = pp.ProductID" +
" where partnumber like '6%'";

Just use verbatim string (#), copy your query and create it like:
string query =
#"Select
[ID]
,[ProductTypeID]
,[SeriesID]
,[PartNumber]
,[Title]
,[SEOFriendlyURLTitle]
,[HTMLDescription]
,[HTMLValueAdded]
,[RoHSCompliant]
,[ULCompliant]
,[CECompliant]
,[Series]
,[BUSINESS_UNIT]
,[PACKAGING_TYPE]
,[PACK_QTY]
,[MOQ]
,[ORDER_MULTIPLE]
,[LEAD_TIME_WEEKS]
,[INTERNATIONAL_HARMONIZE_CODE]
,[ECCN_NUMBER]
,[COUNTRY_OF_ORIGIN]
,[IS_PART_STATIC_SENSITIVE]
,[IS_PART_LEAD_PB_FREE]
,[MOISTURE_SENSITIVITY_LEVEL_MSL]
,[REGISTERABLE]
,[TAPE_WIDTH]
,[TAPE_MATERIAL]
,[QtyOnHand]
,[QtyOnSalesOrder]
,[QtyOnBackOrder]
,[ProductLine]
,[Reach138Compliant]
,[ConflictMinerals]
,[WebEnabled]
,[DateAdded]
,[UpdateDate]
,[Reviewed]
,[ReviewedBy]
,[Deleted]
,[Book]
,[CustomSort]
,[ONEK]
,[FIVEK]
,[TENK]
,[TWENTYFIVEK]
,[Fifty]
,[OneHundred]
,[FiveHundred]
FROM Products.Products
Join
(SELECT Products.Prices.ProductID,
Max(IIf(Products.Prices.Code='ONEK',Products.Prices.Price,Null)) AS ONEK,
Max(IIf(Products.Prices.Code='FIVEK',Products.Prices.Price,Null)) AS FIVEK,
Max(IIf(Products.Prices.Code='TENK',Products.Prices.Price,Null)) AS TENK,
Max(IIf(Products.Prices.Code='TWENTYFIVEK',Products.Prices.Price,Null)) AS TWENTYFIVEK,
Max(IIf(Products.Prices.Code='Fifty',Products.Prices.Price,Null)) AS Fifty,
Max(IIf(Products.Prices.Code='OneHundred',Products.Prices.Price,Null)) AS OneHundred,
Max(IIf(Products.Prices.Code='FiveHundred',Products.Prices.Price,Null)) AS FiveHundred
FROM Products.Prices
GROUP BY Products.Prices.ProductID
) As pp
ON Products.Products.ID = pp.ProductID";
(This will save you from figuring out errors in your concatenation, and would be more readable IMO)

Related

Searching between two views in Wpf C#

I have two views in SQL sever (vHato and vHatoList), what I want is to find the word I write in a text box
this is my code in WPF the first one has no problem; but when I add the last part it gives me "Syntax Error"
var query = db.Database.SqlQuery<vHato>(
$"Select * From vHato Where ((HatoDate Between ('{dtFrom}') And ('{dtTo}'))" +
$" And (HatoFullName Like N'%{txtSearchBox.Text.Trim()}%' Or HatoNo Like " +
$"'%{txtSearchBox.Text.Trim()}%' Or HatoLocation Like N'%{txtSearchBox.Text.Trim()}%'))");
var hato = query.ToList();
DgHato.ItemsSource = hato;
the whole one
var query = db.Database.SqlQuery<vHato>(
$"Select * From vHato Where ((HatoDate Between ('{dtFrom}') And ('{dtTo}'))" +
$" And (HatoFullName Like N'%{txtSearchBox.Text.Trim()}%' Or HatoNo Like " +
$"'%{txtSearchBox.Text.Trim()}%' Or HatoLocation Like N'%{txtSearchBox.Text.Trim()}%'" +
$" Or HatoNo In (Select HatoNo From vHatoList Where (HatoFullName Like N'%{txtSearchBox.Text.Trim()}%')))");
var hato = query.ToList();
DgHato.ItemsSource = hato;
Here's a diff, to make it easier to see the difference between these two queries.
I think you are missing a right round bracket ) at the end of the query. The correspond left round bracket is the first bracket in your query after the where clause. Select * From vHato Where (...)
var query = db.Database.SqlQuery<vHato>(
$"Select * From vHato Where ((HatoDate Between ('{dtFrom}') And ('{dtTo}'))" +
$" And (HatoFullName Like N'%{txtSearchBox.Text.Trim()}%' Or HatoNo Like " +
$"'%{txtSearchBox.Text.Trim()}%' Or HatoLocation Like N'%{txtSearchBox.Text.Trim()}%'" +
$" Or HatoNo In (Select HatoNo From vHatoList Where (HatoFullName Like N'%{txtSearchBox.Text.Trim()}%'))))");
var hato = query.ToList();
DgHato.ItemsSource = hato;

SQL statement that only fetches the newest department which has been allocated

In my database i have the following rows and columns: https://i.imgur.com/ktUZY9d.jpg
My problem is the same employee has 3 different departments, but he is currently only active in 1. How do I change this SQL statement to only include the latest department he is in, which started in 2018 and ends in 2100, as seen by the ALLOCATION_START and ALLOCATION_END?
Query
string agentIdSubQuery = "SELECT DISTINCT " +
"AGENT_ID " +
"FROM " +
"KS_DRIFT.V_AGENT_ALLOCATION " +
"WHERE " +
"LENGTH(AGENT_INITIALS) < 5";
if(queryParams.SnapshotDate.HasValue)
agentIdSubQuery += " AND " + OracleConversion.ToOracleDate(queryParams.SnapshotDate) + " BETWEEN ALLOCATION_START AND ALLOCATION_END";
Update:
Tried alot of different solutions, but it crashes everytime, when i run through the debugger, further Down in this method this Query is causing me to crash:
string sql = "SELECT " +
"age1.* " +
"FROM " +
"KS_DRIFT.V_AGENT_ALLOCATION age1 " +
"INNER JOIN " +
"(" + agentIdSubQuery + ") age2 ON age1.AGENT_ID = age2.AGENT_ID " +
"ORDER BY " +
"AGENT_INITIALS";
Error Message:
{"Error occured during execution of SQL query: SELECT age1.* FROM KS_DRIFT.V_AGENT_ALLOCATION age1 INNER JOIN (SELECT max(DISTINCT AGENT_ID FROM KS_DRIFT.V_AGENT_ALLOCATION WHERE LENGTH(AGENT_INITIALS) < 5 AND '2018-08-15' BETWEEN ALLOCATION_START AND ALLOCATION_END AND (UPPER(AGENT_INITIALS) = 'JKKA')) age2 ON age1.AGENT_ID = age2.AGENT_ID ORDER BY AGENT_INITIALS."}
Also giving me an inner exception:
{"ORA-00904: \"AGE2\".\"AGENT_ID\": ugyldig identifikator"}
Debugging error screeenshot
Order it by the newest start date (descending) and select Top 1!
string agentIdSubQuery = "AGENT_ID " +
"FROM " +
"KS_DRIFT.V_AGENT_ALLOCATION " +
"WHERE " +
"LENGTH(AGENT_INITIALS) < 5 " +
" AND ROWNUM = 1 " +
" ORDER BY ALLOCATION_START DESC";
EDIT, changed Top 1 to Rownum = 1, for Oracle syntax
The table V_AGENT_ALLOCATION contains various departments per agent along with the dates the agent worked there. You want an agent's last department, which you get with Oracle's KEEP LAST. You haven't given us much information on your table, though. Let's say that the department is referenced by an allocation_id:
select
agent_id,
max(id_allocation) keep (dense_rank last order by allocation_start)
as id_current_allocation
from v_agent_allocation
group by agent_id
order by agent_id;
Your error message shows the final generated SQL:
{"Error occurred during execution of SQL query: SELECT age1.* FROM KS_DRIFT.V_AGENT_ALLOCATION age1 INNER JOIN (SELECT max(DISTINCT AGENT_ID FROM KS_DRIFT.V_AGENT_ALLOCATION WHERE LENGTH(AGENT_INITIALS) < 5 AND '2018-08-15' BETWEEN ALLOCATION_START AND ALLOCATION_END AND (UPPER(AGENT_INITIALS) = 'JKKA')) age2 ON age1.AGENT_ID = age2.AGENT_ID ORDER BY AGENT_INITIALS."}
If you format that so that it's readable, you get:
select age1.*
from ks_drift.v_agent_allocation age1
inner join
( select max(distinct agent_id
from ks_drift.v_agent_allocation
where length(agent_initials) < 5
and '2018-08-15' between allocation_start and allocation_end
and (upper(agent_initials) = 'JKKA') ) age2
on age1.agent_id = age2.agent_id
order by agent_initials
Two syntax issues should jump out:
There is a missing closing bracket after max(distinct agent_id (the distinct is also redundant)
The date literal is missing its date keyword - it should be date '2018-08-15' (or better still, a bind variable).
The brackets around (upper(agent_initials) = 'JKKA') are redundant but perhaps they arise from your generator logic and it's easiest to keep them.
I'm not sure how that relates to your 'newest allocated department' requirement, though. Some sample data (not a screenshot) would help.
If you're looking for the current department, you should compare the allocation dates with the current date.
Your query already has this WHERE clause, so it should work just fine for the example provided. But if you might want to specify that you need only ONE row using the ROWNUM special variable clause (assuming it's Oracle).
SELECT DISTINCT AGENT_ID
FROM KS_DRIFT.V_AGENT_ALLOCATION
WHERE LENGTH(AGENT_INITIALS) < 5
AND ALLOCATION_START < CURRENT_DATE AND CURRENT_DATE < ALLOCATION_END
AND ROWNUM = 1

how to insert from different inputs

i am trying to insert different values into a table from my database , i retrieve these values from different tables , input from textBox in Windows form etc ..
but the syntax of my query is not correct , i want to know if there is a possiblity to insert these inputs in one query :
String query4 = #"INSERT INTO FACFIN
(Nom_pren_RS,trimestre,exercice,Nb_factures,Prix_total_HT)
values
('" + textBox1.Text + "','" + textBox3.Text + "','" + textBox2.Text + "',
SELECT cast(count(trimestre) AS varchar(6)) AS Nb_factures FROM facture
WHERE
(facture.Nom_pren_RS='" + textBox1.Text + "'),
SELECT cast(SUM (cast(Prix_vente_HT AS BIGINT ))AS varchar(15))
from facture
where (facture.Nom_pren_RS='" + textBox1.Text + "') ) ";
i know that there is a risk of sql injection and i know that i have to use parameters but i just wanted to test the code to see if it does insert , the syntax of the insert is probably wrong
the nb_factures it should be varchar(6) so i casted it
the column Prix_vente_HT in table facture is varchar so i casted it
to BIGINT to execute the SUM and then casted the SUM to varchar
because the Prix_total_HT should be varchar in the table FACFIN
You cannot add a select statement to a values list, instead this select statement keeps your aggrigates but brings the text box values into a single select statement. If you need to pull rows from multiple tables you can also do a UNION on the select section.
String query4 = #"INSERT INTO FACFIN (Nom_pren_RS,trimestre,exercice,Nb_factures,Prix_total_HT)
SELECT '" + textBox1.Text + "','" + textBox3.Text + "','" + textBox2.Text + "', cast(count(trimestre) AS varchar(6)) AS Nb_factures ,
cast(SUM (cast(Prix_vente_HT AS BIGINT ))AS varchar(15)) as Prix_total_HT
FROM facture
WHERE (facture.Nom_pren_RS='" + textBox1.Text + "')";
The result would look something like this to SQL Server
INSERT INTO FACFIN (Nom_pren_RS,trimestre,exercice,Nb_factures,Prix_total_HT)
SELECT
'TEXT_BOX_1_VALUE','TEXT_BOX_3_VALUE','TEXT_BOX_2_VALUE',
cast(count(trimestre) AS varchar(6)) AS Nb_factures, cast(SUM (cast(Prix_vente_HT AS BIGINT ))AS varchar(15)) as Prix_total_HT
FROM facture WHERE (facture.Nom_pren_RS='TEXT_BOX_1_VALUE')

Storing an image in sql server 2008 using image location in string

I have an image with location
string Imageloc = C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\Sample Pictures\\Sunset.jpg
and i use the following query to insert the image in DB
"UPDATE Employee SET Image = '(SELECT * FROM OPENROWSET(BULK N'" + Imageloc + "', SINGLE_BLOB) as Image)' WHERE EmployeeID = (SELECT MAX(EmployeeID) FROM Employee";
I get the following exception
Incorrect syntax near '\\'.\r\nIncorrect syntax near 'Employee'
Please tell me how to solve it... I dont know how to replace '\\' from the string to '\'
Did you mean:
"UPDATE Employee SET Image =
'(SELECT * FROM OPENROWSET(BULK N'" + Imageloc + "', SINGLE_BLOB) as Image)'
WHERE EmployeeID = (SELECT MAX(EmployeeID) FROM Employee)";
^

Using CTE on SQL Server Compact 3.5

This is my first post on stackoverflow, I hope one of many!
My question is this: I'm using CTE in a query to detect and remove duplicate records in a table. This query works just fine in SQL Server 2005 / 2008, but in Compact it throws an exception:
There was an error parsing the query.
[ Token line number = 1,Token line
offset = 1,Token in error = WITH ]
This is my query:
SqlCeConnection con = new SqlCeConnection(ConfigurationManager.ConnectionStrings["ADSLConnectionString"].ConnectionString);
SqlCeCommand command = new SqlCeCommand();
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "WITH Dublicates_CTE(Username, accountid)" +
" AS" +
" (" +
" SELECT UserName,min(accountid)" +
" FROM Accounts" +
" GROUP BY username" +
" HAVING Count(*) > 1" +
" )" +
" DELETE FROM Accounts" +
" WHERE accountid IN (" +
" SELECT Accounts.accountid" +
" FROM Accounts" +
" INNER JOIN Dublicates_CTE" +
" ON Accounts.Username = Dublicates_CTE.Username" +
" AND Accounts.accountid <> Dublicates_CTE.accountid" +
" ) ";
con.Open();
command.ExecuteNonQuery();
Am I missing something, or does CTE not work on SQL Server Compact?
You can probably just nest the query, something like this (may have some syntax problems):
DELETE FROM Accounts
WHERE accountid IN (
SELECT Accounts.accountid
FROM Accounts
INNER JOIN (
SELECT UserName,min(accountid) accountid
FROM Accounts
GROUP BY username
HAVING Count(*) > 1
) Dublicates_CTE
ON Accounts.Username = Dublicates_CTE.Username
AND Accounts.accountid <> Dublicates_CTE.accountid
)
some things are not supported by the mobile version CTE and store procs for example will not work on the mobile version. You could use the express version which is also free
For the future here is a good link Differences Between SQL Server Compact and SQL Server
Some proof regarding whether SQL Compact 3.5's TSQL subset can use Common Table Expressions:
Tested with Visual Studio 2010 and a new SQL Compact .sdf file.

Categories

Resources