Syntax error (missing operator) in query expression '@ID = @@IDENTITY'

前端 未结 3 773
离开以前
离开以前 2021-01-26 05:57

I have given valuable advise from here

But as subject title says I am receiving error in the btnLogin method, related to my previous question but really the same problem

相关标签:
3条回答
  • 2021-01-26 06:40

    In first login method, you override the commandtext, by setting it twice:

    cmd.CommandText = "INSERT INTO LoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (@UserName, @LoggedInDate, @LoggedInTime)";
    cmd.CommandText = "SELECT @ID = @@IDENTITY"; 
    

    In 'update 2', you are concatting the SELECT-statement right after the INSERT-statement, resulting in the following SQL:

    INSERT INTO LoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (@UserName, @LoggedInDate, @LoggedInTime)SELECT @ID = @@IDENTITY
    

    You must set an ';' at the end of the INSERT-statement, before the 'SELECT'.

    And btw. use SCOPE_IDENTITY(), instead of @@IDENTITY, see http://msdn.microsoft.com/en-us/library/ms190315.aspx and SQL: How to get the id of values I just INSERTed?

    Also, here is an similar question, showing the correct way to execute the command: How to get last inserted id?

    0 讨论(0)
  • 2021-01-26 06:45

    It appears that you may have an error in your code. You set the Text of the cmd to the first line, then completely replace it with the second one:

    cmd.CommandText = "INSERT INTO LoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (@UserName, @LoggedInDate, @LoggedInTime)";
    cmd.CommandText = "SELECT @ID = @@IDENTITY"; 
    

    So you are effectively only executing:

    cmd.CommandText = "SELECT @ID = @@IDENTITY"; 
    
    0 讨论(0)
  • 2021-01-26 06:52

    If you are thinking of fetching the user id, you have to combine both the statments in to a single batch

     cmd.CommandText = "INSERT INTO LoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (@UserName, @LoggedInDate, @LoggedInTime) SELECT @@IDENTITY";
    
    0 讨论(0)
提交回复
热议问题