2

I want to generate access token if username and password will match in users table. But how can I use previous returned value to next insert query? I have marked missing value with ###I don't know###.

CREATE PROCEDURE [dbo].[GetAccessToken]
    @userId varchar(50),
    @password varchar(50)
AS
   SELECT Id 
   FROM Users 
   WHERE UserId = @userId AND Password = @password 

   IF @@ROWCOUNT != 0 
   BEGIN
       SET @token = NEWID();

       INSERT INTO AccessTokens (Token, UserId) 
       VALUES(CONVERT(varchar(255), @token), ###I Don't Know###)
        END
       RETURN 0
   END

Please help me. Thanks, in advance.

4

3 回答 3

2

只需将@userId作为您的第二个参数传递给INSERT

INSERT INTO AccessTokens (Token, UserId) 
VALUES(CONVERT(varchar(255), @token), @userId)
于 2013-04-20T08:49:59.397 回答
1

使用带有 INSERT .. SELECT .. 模式的选项

CREATE PROCEDURE [dbo].[GetAccessToken]
@userId varchar(50),
@password varchar(50)
AS
BEGIN
  INSERT INTO AccessTokens (Token, UserId)
  SELECT CONVERT(varchar(255), NEWID()), Id
  FROM Users 
  WHERE UserId = @userId AND Password = @password
END
于 2013-04-20T10:10:14.343 回答
1

尝试这个:

CREATE PROCEDURE [dbo].[GetAccessToken]
    @userId varchar(50),
    @password varchar(50)
AS
   DECLARE @ID INT
   SELECT @ID = Id 
   FROM Users 
   WHERE UserId = @userId AND Password = @password 

   IF (@ID IS NOT NULL )
   BEGIN
       SET @token = NEWID();

       INSERT INTO AccessTokens (Token, UserId) 
       VALUES(CONVERT(varchar(255), @token), @ID)

       RETURN 0
   END
于 2013-04-20T08:47:13.477 回答