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

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/

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)

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

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) " +

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')

Select highest number from table when number stored as string?

I'm trying to write a windows forms app in C# .Net 4 it connects to a SQL Server 2008 database and I want to Select highest number from a table where the number is stored as string!
string SQL = "select MAX(CONVERT(int, myField)) from myTable where myCode = '" + theCust + "'";
I have also tried Max(CAST(myField as Int)) in the select statement but both fail to return anything even though the Database has for the theCust two rows with 10001 and 10002. The Error i Get is "Enumeration yielded no results"
What am I doing wrong?
I'm using the in built System.Data.SqlClient and if I just do a
string SQL = "select myField from myTable where myCode = '" + theCust + "'";
it returns both numbers as strings. I know I could sort them in code but if the Database gets large that would not be a good approach!
I just tried it again with an int Field in the db and still got the same error! Is Max the wrong thing to be using?
You can try it like this:
SELECT TOP 1 CAST(MyColumn AS int) AS TheMax
FROM MyTable
ORDER BY TheMax DESC
So (using the sloppy method, always paramaterize!)
String sql = "SELECT TOP 1 CAST(MyColumn AS int) AS TheMax FROM MyTable WHERE MyParam = '" + param + "' ORDER BY TheMax Desc";
//Fill DataAdapter/DataReader etc.
Have this function in your database(s):
CREATE FUNCTION dbo.IsAllDigits (#MyString VARCHAR(8000))
RETURNS TABLE AS
RETURN (
SELECT CASE
WHEN #MyString NOT LIKE '%[^0-9]%'
THEN 1
ELSE 0
END AS IsAllDigits
)
because it's better than the in-build ISNUMERIC() in T-SQL.
Then you can use this query to get set of strings that convert to integer types without errors, and filter them like with TOP 1.
SELECT TOP 1 MyColumn AS TheMax
FROM MyTable
WHERE IsAllDigits(MyColumn)=1
ORDER BY MyColumn DESC

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