为什么在构建SQL命令时使用地址符号@?
可能的重复:
.NET 字符串前面的 @ 是什么?
这个 SQL 命令中的 @
是做什么的?它的第一次和第二次出现会起到相同的作用吗?
static DataTable StaffsGetProjectIDHRCoordinators(SqlConnection conn, string targetDatabase)
{
try
{
SqlCommand cmd = new SqlCommand(@"
SELECT DISTINCT Staff.*
FROM Staff
INNER JOIN " + targetDatabase.Replace("'", "''") + @".dbo.ProjectHRCoordinator ProjectHRCoordinator
ON Staff.StaffID = ProjectHRCoordinator.HRCoordinatorStaffID
ORDER BY Staff.FName, Staff.LName", conn);
return ExecuteDataTable(cmd);
}
finally
{
if (conn.State != ConnectionState.Closed) conn.Close();
}
}
我只是熟悉声明存储过程的参数时的 @
符号。
Possible Duplicate:
What's the @ in front of a string for .NET?
What is that @
in this SQL command doing? Would its first and second occurrence serve the same purpose?
static DataTable StaffsGetProjectIDHRCoordinators(SqlConnection conn, string targetDatabase)
{
try
{
SqlCommand cmd = new SqlCommand(@"
SELECT DISTINCT Staff.*
FROM Staff
INNER JOIN " + targetDatabase.Replace("'", "''") + @".dbo.ProjectHRCoordinator ProjectHRCoordinator
ON Staff.StaffID = ProjectHRCoordinator.HRCoordinatorStaffID
ORDER BY Staff.FName, Staff.LName", conn);
return ExecuteDataTable(cmd);
}
finally
{
if (conn.State != ConnectionState.Closed) conn.Close();
}
}
I'm just familiar with the @
signs when declaring a stored procedure's parameters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这意味着该字符串是逐字字符串文字。
\
不会以特殊方式处理。\n
不是新行,而是斜杠和 n。对于路径非常有用。通常,要获得包含
C:\Windows\myfile.txt
的字符串,您需要编写"C:\\Windows\\myfile.txt"
或逐字字符串文字@“C:\Windows\myfile.txt”
。2.4.4.5 字符串文字:
我将补充一点,在您引用的 SQL 块中,它用于能够在多行中编写脚本,而无需关闭字符串的每一行。所以
你可以写
注意这两个字符串是非常不同的!第二个包含行尾和对齐空格,但在 SQL 中这不是问题(SQL 中许多地方都会忽略空格)。
您有可能在一行中编写了 SQL 命令。那么
@
就完全没用了,但是许多程序员采用“安全总比后悔好”的方式,并且相当随意地使用它,特别是当他们从其他可能包含\ escapes:-)
It means the string is a verbatim string literal. The
\
won't be treated in a special way.\n
isn't new line, it's slash and n. Very useful for paths.Normally to have a string containing
C:\Windows\myfile.txt
you would need to write"C:\\Windows\\myfile.txt"
OR with verbatim string literals@"C:\Windows\myfile.txt"
.This is covered in 2.4.4.5 String literals of the C# specification:
I'll add that in the block of SQL you quoted it is used to be able to write the script in multiple lines without closing every line the string. So insted of
you can write
Be aware that the two strings are very different! The second one contains the end-of-lines and the alignment spaces, but in SQL this isn't a problem (empty space is ignored in many places in SQL).
There is a chance that you wrote you SQL command in a single line. Then the
@
was totally useless, but many programmers adopt a "better safe than sorry" and sprinkle it quite liberally, especially when they are pasting text from somewhere else that could contain\ escapes
:-)