Short:
SQL statement in my C# code is not working. with(nolock) is breaking the code.
Detailed:
Below are my errors and the code where I am getting the error. The code is supposed to connect to my SQL Server database (connection code works fine) then run a query. This query will get the ip addresses of all events that have a uri of “blah”. The issue seems to be my with(nolock) command that I am required to use. I have to use it as it’s a group standard for all T-SQL queries.
I googled around for a while but nothing seems to fit my issue and the fixes I found haven’t worked yet. Any help with my code or links would be greatly appreciated.
Error:
System.Data.SqlClient.SqlException was caught Message=Incorrect
syntax near the keyword ‘with’. If this statement is a common table
expression, an xmlnamespaces clause or a change tracking context
clause, the previous statement must be terminated with a semicolon.
Source=.Net SqlClient Data Provider ErrorCode=-2146232060 Class=15
LineNumber=1 Number=319 Procedure=”” Server= State=1
Code:
try
{
//create sql reader to display data
SqlDataReader myReader = null;
//create string to enter data into database
string insString = @"select c_ip from @dates with(nolock) where cs_uri like 'blah'";
SqlCommand myCommand = new SqlCommand(insString, DbConnection);
//populate and sanitize parameters
myCommand.Parameters.Add("@dates", SqlDbType.VarChar, 100);
myCommand.Parameters["@dates"].Value = currentdate;
//execute the command
myReader = myCommand.ExecuteReader();
//read all results and print them to output
while (myReader.Read())
{
//get IPs
String ipmix = myReader["c_ip"].ToString();
mainIPs.Add(ipmix);
}
}
catch (Exception e)
{
Console.WriteLine("The query connection to the datebase has timed out.\n");
Console.WriteLine(e.ToString());
Console.ReadLine();
}
Solution:
Change code from:
//create string to enter data into database
string insString = @"select c_ip from @dates with(nolock) where cs_uri like 'blah'";
to:
//create string to enter data into database
string insString = @"select c_ip from " + currentdate + " with(nolock) where cs_uri like '%blah'";
Get rid of the parameter code and add the tablename in when you build your select statement