Note that there are some explanatory texts on larger screens.

plurals
  1. POC# T-SQL statement includes "with(nolock)" error
    primarykey
    data
    text
    <p>Short:</p> <p>SQL statement in my C# code is not working. <code>with(nolock)</code> is breaking the code.</p> <p>Detailed:</p> <p>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 <code>with(nolock)</code> command that I am required to use. I have to use it as it's a group standard for all T-SQL queries. </p> <p>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. </p> <p>Error:</p> <blockquote> <p>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.<br> Source=.Net SqlClient Data Provider ErrorCode=-2146232060 Class=15 LineNumber=1 Number=319 Procedure="" Server= State=1</p> </blockquote> <p>Code:</p> <pre><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(); } </code></pre> <p>Solution:</p> <p>Change code from:</p> <pre><code>//create string to enter data into database string insString = @"select c_ip from @dates with(nolock) where cs_uri like 'blah'"; </code></pre> <p>to:</p> <pre><code>//create string to enter data into database string insString = @"select c_ip from " + currentdate + " with(nolock) where cs_uri like '%blah'"; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload