开发者

If and Null sql statements

UPDATE: Is this statement correct

  public void CheckReputationIfNull()
{
    StringBuilder sb = new StringBuilder();
    sb.Append("DECLARE @isReputationNull int");
    sb.Append(" SET @isReputationNull=( SELECT Reputation");
    sb.Append(" FROM 开发者_开发知识库Users u");
    sb.Append(" INNER JOIN Comments c ON c.UsersID = u.UsersID");
    sb.Append(" WHERE c.CommentsID = @CommentsID)");

sb.Append(" BEGIN IF ( @isReputationNull IS NULL)");
sb.Append("UPDATE u ");
sb.Append(" SET Reputation = 0");
sb.Append(" FROM Users u");
sb.Append(" END");

using (SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString))
{
    SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
    cmd.Parameters.Add("@CommentsID", SqlDbType.Int).Value = commentID;
    conn.Open();
    cmd.ExecuteNonQuery();
}

}


ISNULL is a function, so you can do:

ISNULL(MyColumn, 'alternative value')

What you want to do is:

IF (MyColumn IS NULL)

Which is checking if the column is NULL.


Simpler, single statement, less prone to errors:

UPDATE Users SET Reputation = COALESCE(Reputation,0) WHERE UserID = @UserID

Or, update your table definition so that Reputation isn't nullable in the first place (and optionally, so that it defaults to 0)


Or, to combine it with your other question (I'm still not sure you shouldn't have just updated/amended that one), you could have:

UPDATE Users SET Reputation = COALESCE(Reputation,0) + @NewReputation
   WHERE UserID = (select UserID from Comments where CommentID = @CommentID)


IF (@isReputationNull IS NULL)
BEGIN
...
END

You need a space between IS and NULL. Also BEGIN is after the IF statement


Use this:

 sb.Append(" IF @isReputationNull IS NULL BEGIN");

ISNULL - is a function in select clause, and you don't need it. Also you should move the BEGIN keyword after the IF statement.


Firstly, you need to move the BEGIN on the next line after the IF. The syntax for IF in SQL is:

DECLARE @test INT
SET @test = 1

IF (@test = 1) 
BEGIN
    PRINT 'test is equal to one'
END

Secondly, you have not provided a WHERE condition in your update statement. If you execute your statement as it currently is, it will update the reputation for all users in the table, possibly causing you to lose data. If you are only looking to initialize the reputation for that specific user who posted the comment, you need to include a WHERE UserID = @UserID (you can populate this variable in the first query).

Also, if you heavily use parameterized queries, I would encourage you to create the queries directly in an SQL Editor first (such as Visual Studio with a data connection or SQL Server Management Studio). This will help you identify and fix any syntax errors before you add the statement to your code, since they become much harder to debug once you have converted them into a string in your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜