Trying to populate a List with the following code:
string sql = ";WITH getUniqueParams AS (" +
"SELECT DISTINCT [a] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [b] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [c] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [d] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [e] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [f] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [g] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [h] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [i] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [j] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [k] AS 'param' FROM table) " +
"SELECT DISTINCT [param] FROM getUniqueParams ORDER BY [param]"; //the result of this statement to be stored in a string
List<string> lUniqueParams = new List<string>();
// set up SQL connection and command
using (SqlConnection conn = new SqlConnection(#"Data Source=server;Initial Catalog=db;Integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand(sqlGetUniqueParams, conn))
{
conn.Open();
// get a SqlDataReader to read multiple rows
using (SqlDataReader rdr = cmd.ExecuteReader()) //getting exception here when debugging
{
// while there are more result rows.....
while (rdr.Read())
{
// grab the 0-index value from the result row
lUniqueParams.Add(rdr.GetString(0));
}
}
conn.Close();
conn.Dispose();
}
Im getting the exception at the following line of code:
using (SqlDataReader rdr = cmd.ExecuteReader())
Is my query not syntactically correct? The query does not perform well, does the rdr only read so long with no results and then give an exception? Am I missing something?
this is working for me please check this: as change table to [table] in your query and also change using (SqlCommand cmd = new SqlCommand(sqlGetUniqueParams, conn)) to using (SqlCommand cmd = new SqlCommand(sql, conn))
string sql = ";WITH getUniqueParams AS (" +
"SELECT DISTINCT [a] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [b] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [c] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [d] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [e] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [f] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [g] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [h] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [i] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [j] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [k] AS 'param' FROM [table]) " +
"SELECT DISTINCT [param] FROM getUniqueParams ORDER BY [param]"; //the result of this statement to be stored in a string
List<string> lUniqueParams = new List<string>();
// set up SQL connection and command
using (SqlConnection conn = new SqlConnection(#"Data Source=server;Initial Catalog=db;Integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
// get a SqlDataReader to read multiple rows
using (SqlDataReader rdr = cmd.ExecuteReader()) //getting exception here when debugging
{
// while there are more result rows.....
while (rdr.Read())
{
// grab the 0-index value from the result row
lUniqueParams.Add(rdr.GetString(0));
}
}
conn.Close();
conn.Dispose();
}
Related
I see 5 records to be inserted, but only 4 are inserted. The last record is not inserted, and I can not figure out why. Copying from one database to the other. First is an access database, the second is a sql server database.
OleDbCommand cmd2 = new OleDbCommand();
OleDbDataReader oledbReader2;
using (cmd2 = new OleDbCommand())
{
query = "SELECT ID, STRAATNAAM, 'NL' AS TAALCODE, PKANCODE, CITY FROM Temp_Unique_Streetnames WHERE TRIM(Temp_Unique_Streetnames.STRAATNAAM) <> '' AND ID > " + lastId.ToString() + " ORDER BY ID";
WriteToFile(query);
cmd2.CommandText = query;
cmd2.CommandType = CommandType.Text;
cmd2.Connection = cn2;
using (oledbReader2 = cmd2.ExecuteReader())
{
while (oledbReader2.Read())
{
try
{
counter += 1;
query = "insert into tblgeo_street ( autoid, street_id, language, country, city, streetname, zip) values (" + counter.ToString() +
" , " + oledbReader2.GetValue(0).ToString() +
" , 'NL', 23, " + oledbReader2.GetValue(4).ToString() +
" , '" + oledbReader2.GetValue(1).ToString().Replace('\'', 'ยด') + "'" +
" , " + oledbReader2.GetValue(3).ToString() + ") ";
OleDbCommand cmd3 = new OleDbCommand(query, cn3);
WriteToFile(query);
cmd3.ExecuteNonQuery();
}
catch (Exception errorException)
{
actionSucceedded = false;
//eventLog1.WriteEntry("Open db threw exception " + errorException.Message);
WriteToFile("insert tblgeo_street threw exception " + errorException.Message);
}
}
}
}
Old SQL:
SELECT
[FileName], [FilePath]
FROM
dbo.[tb_CrawlData] cr
WHERE
cr.Content LIKE '%' + (SELECT content
FROM [tb_CrawlData]
WHERE Content LIKE '%test1%') + '%'
GROUP BY
cr.FileName, [FilePath]
ORDER BY
cr.FileName
Old C# SQL query:
Sqlquery = "SELECT [FileName], [FilePath]"
+ " FROM [tb_CrawlData] cr "
+ " WHERE cr.Content like '%' + (" + Sqlquery.Substring(Sqlquery.IndexOf(" SELECT") + 1) + ") + '%' ";
Sqlquery += " GROUP BY cr.FileName,[FilePath]"
+ " ORDER BY cr.FileName ";
New SQL:
select
[FileName], [FilePath]
from
dbo.[tb_CrawlData] cr
where exists (select 1
from [tb_CrawlData] cd
where cd.Content like '%data%'
and cr.Content like '%' + cd.Content + '%')
group by
cr.FileName, [FilePath]
order by
count(*) desc, cr.FileName
New C# SQL query:
The new sql, I am not so sure how to modify for c#.
We have to use the SqlCommand class.
string sql = "select
[FileName], [FilePath]
from
dbo.[tb_CrawlData] cr
where exists (select 1
from [tb_CrawlData] cd
where cd.Content like '%data%'
and cr.Content like '%' + cd.Content + '%')
group by
cr.FileName, [FilePath]
order by
count(*) desc, cr.FileName"
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
}
Use QueryFirst. You can run your SQL directly in your C# application.
disclaimer : which I wrote :-)
In this void, I have selected the transaction. Example there are 3 rows in the database that has a PONo of 17, I want to show only one row in the list view. Is it possible?
void GetSupply()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT Supplier.SupplierName, PurchaseOrder.PONo, PurchaseOrder.PODate, " +
"PurchaseOrder.PODateReceived, PurchaseOrder.PODeliveryDate, PurchaseOrder.POPaymentMethod, " +
"PurchaseOrder.POReceiptNo, PurchaseOrderDetails.POAmount, PurchaseOrder.POPaymentDate, " +
"PurchaseOrder.POStatus FROM PurchaseOrder INNER JOIN PurchaseOrderDetails " +
"ON PurchaseOrder.PONo = PurchaseOrderDetails.PONo INNER JOIN Supplier ON " +
"PurchaseOrder.SupplierNo = Supplier.SupplierID " +
"ORDER BY PurchaseOrder.PODate DESC";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "PurchaseOrderDetails");
lvPO.DataSource = ds;
lvPO.DataBind();
con.Close();
}
It looks like this for now
I want to show it like this
You can try to use select DISTINCT ie,
cmd.CommandText = "SELECT DISTINCT Supplier.SupplierName, PurchaseOrder.PONo, PurchaseOrder.PODate, " +
"PurchaseOrder.PODateReceived, PurchaseOrder.PODeliveryDate, " +
"FROM PurchaseOrder INNER JOIN PurchaseOrderDetails " +
"ON PurchaseOrder.PONo = PurchaseOrderDetails.PONo INNER JOIN Supplier ON " +
"PurchaseOrder.SupplierNo = Supplier.SupplierID " +
"ORDER BY PurchaseOrder.PODate DESC";
or try to use GROUP BY
cmd.CommandText = "SELECT Supplier.SupplierName, PurchaseOrder.PONo, PurchaseOrder.PODate, " +
"PurchaseOrder.PODateReceived, PurchaseOrder.PODeliveryDate, " +
"FROM PurchaseOrder INNER JOIN PurchaseOrderDetails " +
"ON PurchaseOrder.PONo = PurchaseOrderDetails.PONo INNER JOIN Supplier ON " +
"PurchaseOrder.SupplierNo = Supplier.SupplierID " +
"GROUP BY PurchaseOrder.PONo,Supplier.SupplierName, PurchaseOrder.PODateReceived, PurchaseOrder.PODeliveryDate ORDER BY PurchaseOrder.PODate DESC";
My problem is I am trying to insert into a table by using 2 where statements in my Sql Code.
My code:
using (SqlConnection conn = new SqlConnection(#"Connection String"))
{
conn.Open();
using (var cmd = new SqlCommand(#"INSERT INTO AssignPlan
(Reps, Sets, WeightOrTime, Date, MemberId, ExerciseId)
Select #Reps, #Sets, #WeightOrTime, #Date,
Members.MemberId From Members Where Members.Username = #Username,
ExerciseDisplay.ExerciseId From ExerciseDisplay
Where ExerciseDisplay.ExerciseName = #Exercise", conn))
{
cmd.Parameters.AddWithValue("#Reps", txtReps.Text);
cmd.Parameters.AddWithValue("#Sets", txtSets.Text);
cmd.Parameters.AddWithValue("#WeightOrTime", txtWeight.Text);
cmd.Parameters.AddWithValue("#Date", txtDate.Text);
cmd.Parameters.AddWithValue("#Username", lblRegistered.Text);
cmd.Parameters.AddWithValue("#Exercise", txtName.Text);
cmd.ExecuteNonQuery();
Response.Redirect("Success.aspx");
}
conn.Close();
Any ideas on how to rephrase my SQL statement? Any help would be greatly appreciated!
Assuming that there's no relationship between Members and ExerciseDisplay you could do a cross-join and filter the results:
using (var cmd = new SqlCommand(
" INSERT INTO AssignPlan " +
" (Reps, Sets, WeightOrTime, Date, MemberId, ExerciseId) " +
" Select " +
" #Reps, #Sets, #WeightOrTime, #Date, Members.MemberId, ExerciseDisplay.ExerciseId " +
" From Members, ExerciseDisplay " +
" Where ExerciseDisplay.ExerciseName = #Exercise " +
" AND Members.Username = #Username ", conn))
or, since you're just pulling one value from each table, a subquery should work as well:
using (var cmd = new SqlCommand(
" INSERT INTO AssignPlan " +
" (Reps, Sets, WeightOrTime, Date, MemberId, ExerciseId) " +
" Select " +
" #Reps, #Sets, #WeightOrTime, #Date, " +
" (SELECT MemberId FROM Members WHERE Username = #Username), " +
" (SELECT ExerciseId FROM ExerciseDisplay WHERE ExerciseName = #Exercise) "
, conn))
But that requires that each subquery only returns one value.
I created a query to insert into two ms access tables at a time in c#. I got the exception
{System.Data.OleDb.OleDbException: Characters found after end of SQL
statement. at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult
hr) at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
dbParams, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object&
executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior
behavior, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior
behavior, String method) at
System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at
CompanyDetails.Model.CompanyDetailsModel.setCompanyDetailsToDB(CompanyDetailsDataList
_cmpDetailsList) in E:\Project\PBAttendence\ModifyPrivileage\CompanyDetails\Model\CompanyDetailsModel.cs:line
62}
my sample code is given below please solve my problem. sorry for my bad English.
int companyID = _cmpDetailsList[0].CompanyID;
string companyName = _cmpDetailsList[0].CompanyName;
string contactID = _cmpDetailsList[0].ContactID;
string companyAddress = _cmpDetailsList[0].CompanyAddress;
if (companyID == -1)
{
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity;" + "); ", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
else
{
OleDbCommand upcmd = new OleDbCommand("update CompanyDetails set [CompanyName] = '" + companyName + "',[CompanyAddress] = '" + companyAddress + "',[ContactID] = '" + contactID + "' where [CompanyID] = #cmpID;", conn);
conn.Open();
upcmd.Parameters.AddWithValue("#cmpID", companyID);
upcmd.ExecuteNonQuery();
conn.Close();
}
now i split into two insert command but i got the error {System.Data.OleDb.OleDbException: Syntax error. in query expression 'Select [UserID] from UserDetails;
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
OleDbCommand cmd1 = new OleDbCommand("Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity" + ");", conn);
conn.Open();
cmd1.ExecuteNonQuery();
conn.Close();
The problem is this line of code:
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity;" + "); ", conn);
You have two insert statements in the same OleDbCommand. Try to move this into two different steps:
Insert into CompanyDetails table
Insert into UserCompanyDetails table
Hope this helps you
First of all , it would have been easier with the raw sql command then your code generating the sql.
You might consider making a stored procedure since your command is getting kinda complex
If i'm correct , what you are currently trying to do is :
Insert into table1(x,y,z) values a,b,c;
Insert into table2(x,y) values select * from table3; , ##identity
The second sql command is invalid in both syntax and logic, your ##identity won't be static since you're inserting new records during your command.
My recommendation would be to do something like this :
Insert into table1(x,y,z) values a,b,c;
declare #table1Id int = ##identity
Insert into table2(x,y) select colA, #table1Id from table3;
You cannot have ; in queries in Access. See http://office.microsoft.com/en-us/access-help/HV080760224.aspx You will have to do the two inserts separately as suggested by #juanreyesv
You will have to do 3 queries,
Do the insert using your sql: "Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "')
Get the ##identity using
Select ##identity and store it in a variable say idnt
Use the identity value obtained in 2. to do the third insert:
"Insert into UserCompanyDetails([UserID],[CompanyID])
Select UserID, " + idnt.ToString() + " from UserDetails"
Refer to http://msdn.microsoft.com/en-us/library/ks9f57t0%28VS.71%29.aspx