它是一个编程的方式来获得SQL关键字(保留字) [英] Is it a programmatic way to get SQL keywords (reserved words)
问题描述
我需要验证在名称的SQL列,这是编程方式创建的 ...
I need to validate the Name of a SQL column, which is created programmatically...
有被对子级2验证规则:
There whould be 2 validation rules:
- 在名称不应该是一个C#的关键字
- 的命名不应该是一个SQL关键字的(SQL Server 2008 R2中)的
- The Name shouldn't be a C# keyword
- The Name shouldn't be a SQL keyword (SQL Server 2008 R2)
作为第一个规则的解决方案,这是不错的:
CSharpCodeProvider 类有 IsValidIdentifier 方式使验证容易的实现。
The CSharpCodeProvider class has the IsValidIdentifier method which makes the implementation of validation easy.
(例如:
string myColumnName = "blabla";
var isValid = _cSharpCodeProvider.IsValidIdentifier(myColumnName);
)
作为第二个规则的解决方案,这是一个痘痘详细:
我发现做谷歌搜索的唯一方法是从的 MSDN - 保留关键字(Transact-SQL中)的SQL Server 2008 R2
The only way I found doing google searches is to take the keywords from MSDN - Reserved Keywords (Transact-SQL) SQL Server 2008 R2
要建立一个字符串[]属性,它会返回所有这些关键字。 ..
To build a string[] property which will return all these keywords...
(例如:
public static class SqlReservedKeywords {
public static string[] SqlServerReservedKeywords {
get { return SqlServerKeywords; }
}
private static readonly string[] SqlServerKeywords = new[] {
"ADD","EXISTS","PRECISION",
//. . .
"EXEC","PIVOT","WITH",
"EXECUTE","PLAN","WRITETEXT"
};
}
//外部代码
//External code
var isValid = SqlReservedKeywords.SqlServerReservedKeywords.Contains(myColumnName);
)
)
您能不能指点我一下第二个验证规则implementantion。
它是一个好的做法呢?
也许存在另一种方式来实现我没有使用Google所...
Can you advice me about implementantion of 2nd validation rule. Is it a good practice? Maybe it exist another way to implement which i didn't found by googling...
推荐答案
由于没有找到你可以调用的C#功能,真正的问题是如何做的SQL保留字的查找。你的实现方式看这里是不是最有效的C#。您应该使用HashSet的 - 快速未经测试的代码示例如下:
Since there is a function you can call for C#, the real question is how to do the lookup for SQL Reserved words. The way you implemented look up here is NOT the most efficient C#. You should use a HashSet -- quick untested code example follows:
public static class SqlReservedKeywords {
public bool isReserved(string in)
{
return SqlServerKeywords.Contains(in.ToUpper());
}
private static HashSet<string> SqlServerKeywords = new HashSet<string>();
static SqlReservedKeywords()
{
SqlServerKeywords.Add("ADD");
SqlServerKeywords.Add("EXISTS");
SqlServerKeywords.Add("PRECISION");
//. . .
SqlServerKeywords.Add("EXEC");
SqlServerKeywords.Add("PIVOT");
SqlServerKeywords.Add("WITH");
SqlServerKeywords.Add("EXECUTE");
SqlServerKeywords.Add("PLAN");
SqlServerKeywords.Add("WRITETEXT");
}
}
下面是一个不错的文章(由@theburningmonk)显示使用包含
Here is a nice article (by @theburningmonk) showing how fast HashSet is when using Contains
(对于那些不想点击,HashSet的是零)
(For those that don't want to click, HashSet is zero)
http://theburningmonk.com/2011/03/hashset- VS-列表-VS-字典/
这篇关于它是一个编程的方式来获得SQL关键字(保留字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!