【发布时间】:2011-12-28 21:48:00
【问题描述】:
短:
我的 C# 代码中的 SQL 语句不起作用。 with(nolock) 正在破解密码。
详细说明:
以下是我的错误和出现错误的代码。该代码应该连接到我的 SQL Server 数据库(连接代码工作正常)然后运行查询。此查询将获取所有具有“blah”uri 的事件的 IP 地址。问题似乎是我需要使用的with(nolock) 命令。我必须使用它,因为它是所有 T-SQL 查询的组标准。
我用谷歌搜索了一段时间,但似乎没有什么适合我的问题,而且我发现的修复方法还没有奏效。对我的代码或链接的任何帮助将不胜感激。
错误:
System.Data.SqlClient.SqlException 被捕获 Message=Incorrect 关键字'with'附近的语法。如果这个语句是公用表 表达式、xmlnamespaces 子句或更改跟踪上下文 子句,前面的语句必须以分号结束。
源=.Net SqlClient 数据提供程序错误代码=-2146232060 类=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'";
【问题讨论】:
-
不是with,而是@dates
-
感谢您输入 StingyJack!有什么建议吗?
-
@toosweetnitemare:您知道并正在处理 WITH NOLOCK 会导致您错过已经提交的行吗?
-
@Anders UP:是的,我知道。正在访问的 DB 不断被写入,我们更关心正在完成的写入,然后丢失一些已提交的行。谢谢你提出这个细节。我相信这个线程的未来读者会喜欢它! :D