Sql 关键字搜索以包括Uniqueidentifier字段
我想让用户通过指定要查找的关键字来搜索数据库中的行。我想在几个字段中查找这个关键字,其中一个字段是uniqueidentifier。问题是,如果关键字不是GUID,我会收到以下错误消息:Sql 关键字搜索以包括Uniqueidentifier字段,sql,sql-server,uniqueidentifier,Sql,Sql Server,Uniqueidentifier,我想让用户通过指定要查找的关键字来搜索数据库中的行。我想在几个字段中查找这个关键字,其中一个字段是uniqueidentifier。问题是,如果关键字不是GUID,我会收到以下错误消息: Conversion failed when converting from a character string to uniqueidentifier 我用于运行搜索的SQL如下所示: // do not use string sql = @"SELECT * FROM [
Conversion failed when converting from a character string to uniqueidentifier
我用于运行搜索的SQL如下所示:
// do not use
string sql = @"SELECT *
FROM [MyTable]
WHERE [MyTable].[TableID] = '" + keyword + "'";
警告:这只是示例代码-不要像这样编写sql命令,因为它会造成安全风险
如何编写SQL select语句,使其在
关键字
不是GUID时不会失败?这对您有用吗
string sql = @"SELECT *
FROM [MyTable]
WHERE convert(varchar,[MyTable].[TableID]) = '" + keyword + "'";
我知道这对你今天没有什么帮助,但可能对未来的读者有所帮助。在SQL Server 2012中,您将能够使用:
但您真正应该做的是将参数作为强类型GUID传递,并在有人输入非GUID的内容时在客户端程序中处理错误(使用
try/catch
)。为什么不在运行查询之前简单地检查关键字
是否是有效的GUID?您可以使用类似正则表达式的@“^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$”
。
string sql;
Guid id;
if (Guid.TryParse(keyword, out id))
{
sql = @"SELECT *
FROM [MyTable]
WHERE [MyTable].[TableID] = '" + keyword + "'";
}
else
{
sql = //search by other way
}
string sql;
Guid id;
if (Guid.TryParse(keyword, out id))
{
sql = @"SELECT *
FROM [MyTable]
WHERE [MyTable].[TableID] = '" + keyword + "'";
}
else
{
sql = //search by other way
}