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 :-)
Related
Im creating columns using mysql dynamically if column doesnt exist.. I got the code which works in mysql console but when it comes to c# its giving me "Fatal encountered during command execution"
SET #preparedStatement = (SELECT IF(
(SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tableName'
AND table_schema = DATABASE()
AND column_name = 'colName'
) > 0,
"SELECT 1",
"ALTER TABLE `tableName` ADD `colName` TINYINT(1) NULL DEFAULT '0';"
));
PREPARE alterIfNotExists FROM #preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
above code i converted into c# string as
string qry = "SET #preparedStatement = ( SELECT IF( (SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME = '" + tname + "' AND COLUMN_NAME = '" + code + "_C' ) > 0, \"SELECT 1', \"ALTER TABLE " + tname + " ADD " + code + "_C int(3) NOT NULL default '0'; \" )); PREPARE alterIfNotExists FROM #preparedStatement; EXECUTE alterIfNotExists; DEALLOCATE PREPARE alterIfNotExists;";
what's the error getting?
Execution Code:
private void columnCreate_Load(object sender, EventArgs e)
{
string tname = "bca_i"; //for temprory
string code = "BCAXX";//for temprory
string qry = #"SET #preparedStatement = ( SELECT IF( (SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME = '" + tname + "' AND COLUMN_NAME = '" + code + "_C' ) > 0, \"SELECT 1', \"ALTER TABLE " + tname + " ADD " + code + "_C int(3) NOT NULL default '0'; \" )); PREPARE alterIfNotExists FROM #preparedStatement; EXECUTE alterIfNotExists; DEALLOCATE PREPARE alterIfNotExists;";
try
{
using (MySqlConnection conn = new MySqlConnection(ConStr))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(qry, conn))
{
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The part
\"SELECT 1', \"A
does not match your original query at
"SELECT 1",
"A
Do you spot it? You replaced the " after 1 by an '.
I just figured other way for checking column exist.. Just used below query and checked if the column exists iterating through the loop of columns
string last_col = "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME ='" + subCodeText.Text + "'";
where attendance is database and subCodeText.Text is my table name.
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();
}
I am executing a MS Access Query through c#. Below is the query
String SelWHQuery = "SELECT DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours" +
"' WHERE EMPID = '" + Eno +
"'AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") +
"# FROM INOUTPunching";
which is giving below error
{"The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect."}
I need to know:
Why is this not working?
Is there any simplier method?
You should place the FROM clause before the WHERE clause. That is the problem with your query. And you have an extra single quote which should be removed. This is the query you should write:
String SelWHQuery = "SELECT DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours FROM INOUTPunching " +
" WHERE EMPID = '" + Eno +
"'AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") + "#";
And about a simpler method: no, this is the simplest method but it is prone to SQL injection attacks. Replace it with a parameterized query (assuming you have an OldDbCommand name cmd):
String SelWHQuery = "SELECT DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours FROM INOUTPunching " +
" WHERE EMPID = #EmpId AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") + "#";
cmd.CommandType = CommandType.Text;
cmd.CommandText = SelWHQuery;
cmd.Parameters.AddWithValue("#EmpId", Eno);
I am currently trying to use an sql join statement to bring back results needed for my program. When i try to change one of the database names to a variable, it is displaying an exception of "System.Data.SqlClient.SqlException (0X80131904): Incorrect syntax near '.'" Both databases are on the same SQL server. If i use one of the database names in the string, it connects and the statement is executed as intended. This only occurs when i put the database name as a parameter:
using (var command = new SqlCommand("select p.Tablefield, P.TableFeild, es.SynchronousIn, es.SynchronousOut, " +
"es.dddd, es.MessageName, es.MessageDate from database.xxx.xxx es " +
"join #Database.dbo.xxxx p on p.GUID = es.dddd where es.MessageName = #MessageType and " +
"(es.MessageDate >= #date and es.MessageDate < #date)" +
"and es.dddd = #ddddd " +
"order by MessageDate DESC" , connection))
The #Database Parameter is defined afterwards:
command.Parameters.Add("#Database", SqlDbType.NVarChar);
command.Parameters["#Database"].Value = DatabaseName;
Any ideas at all? I know this might not be the best way of doing this, I am pretty new to the SQL aspect of c# and would like to know if this is possible. I have replaced certain fields with XXXX or DDDD as this is a tool i am hoping to write for my company.
You can not pass the database name as a parameter. You can add it using String.Format on the sql command string.
Something like this:
String.Format("select p.Tablefield, P.TableFeild, es.SynchronousIn, es.SynchronousOut, " +
"es.dddd, es.MessageName, es.MessageDate from database.xxx.xxx es " +
"join {0}.dbo.xxxx p on p.GUID = es.dddd where es.MessageName = #MessageType and " +
"(es.MessageDate >= #date and es.MessageDate < #date)" + "and es.dddd = #ddddd " +
"order by MessageDate DESC", DatabaseName);
Check the following:
String.Format("select p.Tablefield, P.TableFeild, es.SynchronousIn, es.SynchronousOut, " +
"es.dddd, es.MessageName, es.MessageDate from database.xxx.xxx es " +
"join {0}.dbo.xxxx p on p.GUID = es.dddd where es.MessageName = #MessageType and " +
"(es.MessageDate >= #date and es.MessageDate < #date)" + "and es.dddd = #ddddd " +
"order by MessageDate DESC", DatabaseName);
You cannot pass the table name as a parameter. You could just insert the table name into the SQL string using string.Format. Something like..
using (var command = new SqlCommand("select p.Tablefield, P.TableFeild, es.SynchronousIn, es.SynchronousOut, " +
"es.dddd, es.MessageName, es.MessageDate from database.xxx.xxx es " +
string.Format("join #{0}.dbo.{1} p on p.GUID = es.dddd where es.MessageName = #MessageType and ",databaseName,tableName) +
"(es.MessageDate >= #date and es.MessageDate < #date)" +
"and es.dddd = #ddddd " +
"order by MessageDate DESC" , connection))
Be sure to check this value for SQL injection if it is in any way manipulated from the user interface.
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