So My issue is that I am getting the error "Incorrect Syntax near the keyword 'With'" I haven't really used the with command much before so I'm not too sure what the issue is relating to. This code will be used in an SSRS report and you'll see where I've put the comments that I will replace those values with parameters. Essentially the order of operation is to create a table of all the users where their branch matches the input provided. the select their "flag" which is just a unique number which allows us to calculate what permissions each user has and convert that to binary, then cross check if that user has the permissions we need and if so create a new table of users with those permissions
Declare @Users table(Names nvarchar(50) not null, Flag int)
Declare @ValidUsers table(Names nvarchar(50) not null)
Declare @Office int
Declare @NumberOfRecords int
Declare @Count int
Declare @IntCount int
DECLARE @Binary AS nvarchar(16);
declare @bit as nvarchar(1);
declare @PermissionSub as nvarchar(1);
declare @Permission as nvarchar(16);
declare @ShouldContinue as bit
set @ShouldContinue = 1;
set @Permission = '0001111111111111'; /* going to pass this value */
set @Count = '1'
set @IntCount = '1'
Set @Office = '3' /* going to pass this value */
Insert into @Users
Select dbUser.usrFullName, udFeeEarnerLicence.purchaseFlag
From udFeeEarnerLicence INNER JOIN
dbUser ON udFeeEarnerLicence.feeUsrId = dbUser.usrID
where dbUser.brId = @Office
select @NumberOfRecords = COUNT(Flag) from @Users
DECLARE @Flag AS int;
select @Flag = Flag from @Users
while(@Count <= @NumberOfRecords)
begin
select @Flag = Flag from @Users where ROW_NUMBER() over (order by Flag) = @Count
WITH A AS (
SELECT 0 AS ORD, @Flag AS NUMBER, CAST('' AS VARCHAR(20)) AS BITS
UNION ALL
SELECT ORD+1, NUMBER/2, CAST(BITS+CAST(NUMBER%2 AS VARCHAR(20)) AS VARCHAR(20))
FROM A
WHERE NUMBER>0)
SELECT @Binary = RIGHT('000000000000000'+ CASE WHEN BITS='' THEN '0' ELSE REVERSE(BITS) END,16)
FROM A
WHERE NUMBER = 0;
while(@IntCount <= 16)
begin
select @bit = SUBSTRING(@Binary, @IntCount, @IntCount + 1)
select @PermissionSub = SUBSTRING(@Permission, @IntCount, @IntCount + 1)
if(@PermissionSub = '1' and @bit != '1') /* if Permission selection is required and user does not have permission*/
begin
SET @ShouldContinue = 0
break;
end
end
Set @IntCount = 0
if(@ShouldContinue = 0)
begin
continue
end
Insert into @ValidUsers
select Names from @Users where ROW_NUMBER() over (order by Flag) = @Count
end
I've just tried to run it again with the ;
before the with and that just bring up another error saying "Windowed functions can only appear in the select or order by clauses"