Best method for determining if a row exists

一个人想着一个人 提交于 2019-12-25 08:28:38

问题


I am using SQL Server and WebMatrix Razor syntax to try and determine is a username is contained within a table called Users.

The logic I wish to have is :

 bool usernameExists = db.QueryValue("SELECT Username from Users where Username = ?", username);
 if(usernameExists.IsEmpty()){ //username is not in table
    Response.Redirect("Register.cshtml");
 }

What is the best practice for going about this?


回答1:


Simplest is probably:

bool usernameExists = db.QueryValue("SELECT usernameExists = CASE WHEN EXISTS 
 (SELECT 1 FROM Users WHERE Username = ?) THEN 1 ELSE 0 END", username);

if (!usernameExists) { Response.Redirect("Register.cshtml"); }

Though I'm speaking strictly from the SQL Server side. I don't know if this is the best approach from the C# side.




回答2:


One approach would be to implement a custom membership provider which authenticates against your own user table. You application is then decoupled from the specifics of user storage and it's a well understood model for user authentication in ASP.NET applications.



来源:https://stackoverflow.com/questions/9649814/best-method-for-determining-if-a-row-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!