Ambiguous column name in c# but not in SQL Server? - c#

I am trying to execute a SQL command via c# but is telling me that I have an ambiguous column name. When I copy the query into SQL Server and execute it, it works fine. But through c#, it tells me
Ambiguous column name 'SPCode'
This is my SQL string in c#:
string yourSQLstring =
"INSERT INTO totalTable (Catalogue, totalTable.SPCode, ProjNo, Quantity, Spare) " +
"SELECT Catalogue, BOMtable.SPCode, ProjNo, SUM(Quantity) AS Quantity, (SELECT CEILING(CAST (.1 * SUM(Quantity) AS FLOAT))) AS Spare FROM MainSuperTable4 " +
"FULL OUTER JOIN BOMtable ON PartNo = Catalogue " +
"WHERE ProjNo= '" + SavingData.instance.projNumber + "' AND SPCode IS NOT NULL " +
"GROUP BY Catalogue, ProjNo, SPCode";
This the code copied into SQL Server and edited to remove c# stuff:
INSERT INTO totalTable (Catalogue, SPCode, ProjNo, Quantity, Spare)
SELECT
Catalogue, SPCode, ProjNo,
SUM(Quantity) AS Quantity,
(SELECT CEILING(CAST (.1 * SUM(Quantity) AS FLOAT))) AS Spare
FROM MainSuperTable4
FULL OUTER JOIN BOMtable ON PartNo = Catalogue
WHERE
ProjNo = 'P140134' AND SPCode IS NOT NULL
GROUP BY
Catalogue, ProjNo, SPCode
Not sure why it would work in SQL Server and then not in C#?
Thanks for any help!

Change your group by to this:
"GROUP BY Catalogue, ProjNo, BOMtable.SPCode";
Change your insert to this:
"INSERT INTO totalTable (Catalogue, SPCode, ProjNo, Quantity, Spare) " +

Related

How to update only the highest id of the same Name in c#.net database

I have this Table Data for my FullSummary Database:
I want to update ONLY the "Name, Price, and Total" for the HIGHEST Id of a selected Name.
If I select "random" the "random" with Id 52 should be the only one that will have the updated data.
I tried:
con.Open();
cmd.CommandText = "UPDATE FullSummary SET Name='" + addRiceTextBox.Text + "', Price='" + addPriceTextBox.Text + "', Total='" + newTotalEdit.Text + "' WHERE(Id, Name) IN(SELECT MAX(Id), Name FROM FullSummary GROUP BY Name)";
cmd.ExecuteNonQuery();
con.Close();
But it gave me this error:
I found the code here: select only rowwith highest id value if there are identical column values
And this one: How can I select the row with the highest ID in MySQL? only selects an item and not update it.
SQL Server doesn't support tuple comparison. So this
WHERE(Id, Name) IN (SELECT MAX(Id), Name FROM FullSummary ...)
Won't work. So you should use a scalar subquery like this (with parameters):
UPDATE FullSummary f
SET Price=#price, Total=#total
WHERE Id = (select max(ID) from FullSummary where name = #name)

SQL Returning rows with max value in column, within a specific range

I'm populating a DataTable in C# using an OleDbDataAdapter, and I am trying to get a query to work without much success.
The communication to/from the server works fine, as is evidenced by the simple query that returns all the records without any filter:
var commandText = string.Format("SELECT IsoShtRevID, LineID, Filename, Revision " +
"FROM dbo.PDSIsometricSheets WHERE SchemaName='{0}'", projectNo);
This gives me a list of about 8000 entries, however there is some redundancy.
There are multiple rows with the same LineID, but each one has a separate Revision value. I'm trying to get only the rows with the highest revision for each LineID, from a range of 0 to 5.
Here are a few of the attempts I've tried so far:
var commandText = string.Format("SELECT * FROM
(SELECT max(Revision) as LatestRev
FROM dbo.PDSIsometricSheets)
WHERE Revision < 5" , projectNo);
var commandText = string.Format("SELECT T.IsoShtRevID, T.LineID, T.Filename, T.Revision
FROM dbo.PDSIsometricSheets T
WHERE Revision =
(SELECT MAX(T1.Revision)
FROM dbo.PDSIsometricSheets T1
WHERE T1.IsoShtRevID = T.IsoShtRevID
)", projectNo);
var commandText = string.Format("SELECT IsoShtRevID, LineID, Filename, MAX(Revision) as LatestRevision
FROM dbo.PDSIsometricSheets WHERE SchemaName='{0}'
GROUP BY LineID, IsoShtRevID, Filename", projectNo);
Here are the questions I've visited so far trying to get this to work:
SQL Select only rows with Max Value on a Column
How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?
Fetch the row which has the Max value for a column
Select Rows with Maximum Column Value group by Another Column
Everything above either returns the same thing as my original query, or just errors out from bad syntax. SQL is the furthest thing from my forte, and I'm trying to figure out if I'm limited in functionality by using a DataAdapter.
UPDATE:
Here's the latest iteration, using some advice from below:
var commandText = string.Format("SELECT IsoShtRevID, LineID, Filename, MAX(Revision) as MaxRevision " +
"FROM dbo.PDSIsometricSheets " +
"WHERE SchemaName='{0}' AND Revision <= 5 AND Revision >= 0" +
"GROUP BY IsoShtRevID, LineID, Filename", projectNo);
This filters out the revision to values between 0 and 5, however there are still multiple rows for LineID, each with different Revision numbers. It's like the Max command is being ignored...
Option 3 should work but if it doesn't is because FileName or IsoShtRevID change across Revisions. In that case, you can do this:
SELECT a.IsoShtRevID ,
a.LineID ,
a.Filename ,
a.Revision
FROM dbo.PDSIsometricSheets a
join (select max(Revision) as Revision, LineID
from dbo.PDSIsometricSheets where SchemaName ='{0}' ) x
join a on a.Revision = x.Revision and a.LineID=x.LineID
WHERE a.SchemaName = '{0}'
Finally got it thanks to the comments, reading more SQL, and viewing my commandstring diligently at runtime for typos.
var commandText = string.Format("SELECT T1.IsoShtRevID, T1.LineID, T1.FileName, T1.Revision " +
"FROM dbo.PDSIsometricSheets T1 " +
"INNER JOIN (" +
"SELECT LineID, MAX(Revision) as MaxRevision " +
"FROM dbo.PDSIsometricSheets " +
"WHERE SchemaName='{0}' AND Revision <= 5 AND Revision >= 0" +
"GROUP BY LineID" +
") T2 " +
"ON T1.LineID = T2.LineID AND T1.Revision = T2.MaxRevision ", projectNo);

add column to existing query with GROUP BY

I have got little issue, I'm trying to put another column klisluz.cena to existing query but its giving me errors that: Column klisluz.cena in command SELECT isnt correct, because its not in GROUP BY, but when I insert it in GROUP BY it throws the same error. Where should I put it ?
Thanks in advance. this is the query:
string sQuery = string.Format("SELECT zajsluz.akce,zajsluz.text,klisluz.pocet,klisluz.cena,klisluz.subkey,zajsluz.ID FROM zajsluz LEFT JOIN klisluz ON zajsluz.ID=klisluz.IDzajsluz WHERE zajsluz.akce= '{0}' and ISNULL(klisluz.subkey, '" + vyberradek + "') = '" + vyberradek + "' GROUP BY klisluz.subkey,zajsluz.akce,zajsluz.text,klisluz.pocet,zajsluz.ID", sZakce);
If your column "cena" is a numeric price value, then you could perform an Aggregate Function on it.
You could try to use the MAX(klisluz.cena) to get the maximum value, or SUM(..) to get a sum any other one that could apply to this column type.
http://msdn.microsoft.com/en-us/library/ms173454.aspx
klisluz.cena is not in the group by.

How to Insert data into self reference table in sql server? [duplicate]

This question already exists:
Insert query for self reference of single table in sql server?
Closed 10 years ago.
What is the the query for inserting data into a self-referencing table. My table has 4 columns: SlNo, Name , ParentId , CurrentBanlance.
I tried this SQL query but it doesn't execute, is there any another way?
INSERT INTO Ptr_AcntInfo
SELECT
'" + txtAcName.Text + "',
(SELECT [SlNo] FROM Ptr_AcntInfo WHERE [Ac_Nm] = '" + cbxAcntGrpName.Text + "'),"+0.00+""
In this query I am getting the below error.
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The query should look like:
"INSERT INTO PTR_ACNTINFO (COL1, COL2)
(SELECT " + txtAcName.Text + ", SINo FROM
PTR_ACNTINFO
WHERE [Ac_Nm]='" + cbxAcntGrpName.Text + "')"
Note this query is vulnerable to SQL Injection attacks.
http://en.wikipedia.org/wiki/SQL_injection
You should use parameterised queries or a stored procedure.
Example:
SQLCommand sqlCommand = new SQLCommand(connection);
sqlCommand.CommandText = "INSERT INTO PTR_ACNTINFO (SELECT $name, SINo FROM
PTR_ACNTINFO WHERE [Ac_Nm]='$accNo')"
sqlCommand.Parameters.AddWithValue("$name", txtAcName.Text);
sqlCommand.Parameters.AddWithValue("$accNo", cbxAcntGrpName.Text);
http://johnhforrest.com/2010/10/parameterized-sql-queries-in-c/

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