C# T-SQL 语句包括“with(nolock)”错误

发布于 2024-12-23 11:45:12 字数 1854 浏览 3 评论 0原文

简而言之:

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

详细:

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

我用谷歌搜索了一段时间,但似乎没有什么适合我的问题,而且我发现的修复还没有起作用。对我的代码或链接的任何帮助将不胜感激。

错误:

捕获了 System.Data.SqlClient.SqlException 消息=不正确 关键字“with”附近的语法。如果这条语句是普通表 表达式、xmlnamespaces 子句或更改跟踪上下文 子句中,前一条语句必须以分号结束。
源=.Net SqlClient 数据提供程序错误代码=-2146232060 类=15 LineNumber=1 编号=319 过程="" 服务器= 状态=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'";

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'";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七七 2024-12-30 11:45:12

它不是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 注入的风险。去掉like,换成equals也会提高查询性能。另外,完全删除参数。

Its not the WITH, its the @dates variable. You are basically creating the statement....

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

Which makes no sense.

Also, your exception message to the user is not really correct. The error could have been any number of things (like "incorrect syntax"), but you are telling them its a timeout issue.

Based on your comment, you should just change the query text to be...

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

As you are generating the currentdate value in code and not from any user input, you are not at risk of SQL injection. Taking out the like and replacing it with an equals will also improve the query performance. Also, remove the parameters entirely.

帅冕 2024-12-30 11:45:12

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

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

string insString = @"select c_ip from " + currentdate + " with(nolock) where cs_uri like 'blah'";
往日情怀 2024-12-30 11:45:12

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

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

您可能想要类似

“从logtable中选择c_ip with(nolock),其中cs_uri像'blah'和log_date=@dates”

不要忘记,如果您使用 DATETIME 字段,则日期是由日期和时间部分组成的,因此您可能还需要构建一个相关的日期范围00:00:0023:59:59 (或使用 currentdate+1 捕获午夜重叠

select c_ip from logtable with(nolock) where (cs_uri like '%blah%') and (log_date between @startdate and @enddate)

you have asked it to select records from a table called @Dates. (where that is the date parameter) - that will evaluate to

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

You probably want something like

"select c_ip from logtable with(nolock) where cs_uri like 'blah' and log_date=@dates"

not forgetting that dates, if you're using DATETIME fields, are made up of a date and time component so you'll probably also want to construct a relevant date range from 00:00:00 to 23:59:59 (or use currentdate+1 to catch the midnight overlap)

That gives you

select c_ip from logtable with(nolock) where (cs_uri like '%blah%') and (log_date between @startdate and @enddate)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文