I have written a stored procedure Where I have written a query to get userid
. There is a separate database for every userid
. So I am trying to run a select query based on this userid obtained from my previous select query in a loop.
And I am trying to assign the columns in this select query to variables declared and use them further. But I am not understanding how to assign these to variables as I am getting errors
USE DATABASE1
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [User].[update_client_details]
AS
DECLARE
@clientdata CURSOR,
@clientid INT,
@SQL VARCHAR(2000),
@uid INT
@isactive INT,
@createdDate Date
BEGIN
SET @clientdata = CURSOR FOR
SELECT clientuserid FROM User.queen_client
OPEN @clientdata
FETCH NEXT
FROM @clientdata INTO @clientid
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = N'SELECT @uid=userid, @isactive=isactive, @createdDate=createddate FROM ['+CAST(@clientid AS NVARCHAR(20))+'].User.queen_user';
EXEC (@SQL)
IF(@isactive = 1)
BEGIN
//do someting//
END
END
CLOSE @clientdata
DEALLOCATE @clientdata
END
if the execute the store procedure it is getting executed and not stopping. If I force stop the execution then I am getting the error as "must declare the scalar variable "uid
""
Query Which I tried
EXEC sys.sp_executesql N'SELECT @uid=userid, @isactive=isactive, @createdDate=createddate FROM ' +QUOTENAME(@clientid)+'.QueenBase.queen_user', N'@clienid int, @uid int OUTPUT, @createDate date OUTPUT';