C#T-SQL语句包含" with(nolock)"错误

时间:2011-12-28 21:48:01

标签: c# sql nolock

短:

我的C#代码中的SQL语句不起作用。 with(nolock)正在打破代码。

详细说明:

以下是我的错误以及我收到错误的代码。代码应该连接到我的SQL Server数据库(连接代码工作正常)然后运行查询。此查询将获取具有uri“blah”的所有事件的ip地址。问题似乎是我需要使用的with(nolock)命令。我必须使用它,因为它是所有T-SQL查询的组标准。

我用谷歌搜索了一段时间,但似乎没有任何东西适合我的问题,我发现的修复工作还没有完成。任何有关我的代码或链接的帮助将不胜感激。

错误:

  

System.Data.SqlClient.SqlException被捕获Message =不正确   关键字'with'附近的语法。如果此语句是公用表   表达式,xmlnamespaces子句或更改跟踪上下文   条款,先前的陈述必须以分号结束   Source = .Net SqlClient Data Provider ErrorCode = -2146232060 Class = 15   LineNumber = 1 Number = 319 Procedure =“”Server = State = 1

代码:

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();
}

解决方案:

更改代码:

//create string to enter data into database
string insString = @"select c_ip from @dates with(nolock) where cs_uri like 'blah'";

为:

//create string to enter data into database
string insString = @"select c_ip from " + currentdate + " with(nolock) where cs_uri like '%blah'";

3 个答案:

答案 0 :(得分:7)

它不是WITH,它是@dates变量。你基本上是在创建声明....

select c_ip from '12/28/2011 15:35:22.997' with(nolock) where cs_uri like 'blah'

这没有任何意义。

此外,您向用户发送的异常消息并不正确。错误可能是任何数量的事情(例如“不正确的语法”),但你告诉他们它是超时问题。

根据您的评论,您只需将查询文字更改为...

string insString = @"select c_ip from " + currentdate + " with(nolock) where cs_uri = 'blah'";

当您在代码中生成currentdate值而不是从任何用户输入生成时,您不会有SQL注入的风险。取出之类并用等号替换它也可以提高查询性能。另外,完全删除参数。

答案 1 :(得分:1)

在构建select语句时删除参数代码并添加表名

string insString = @"select c_ip from " + currentdate + " with(nolock) where cs_uri like 'blah'";

答案 2 :(得分:1)

您已要求它从名为@Dates的表中选择记录。 (这是日期参数) - 将评估为

select 'c_ip from 28-12-2011...'

你可能想要像

这样的东西

“从 logtable 中选择c_ip与(nolock),其中cs_uri喜欢'blah'和log_date = @ dates

如果您使用DATETIME字段,则不要忘记该日期由日期和时间组成,因此您可能还希望构建从00:00:00到{的相关日期范围{1}}(或使用23:59:59来捕捉午夜重叠)

那会给你

currentdate+1