We are currently implimenting row level security by putting part of the Customer's account information in a DB Table. I have been able to do this on a case by case (individual customer) basis, but I tried to script inserting a whole bunch of customers at once using a script. When I run the script just using print commands, everything looks fine. When I run it to actually process the data, things bomb out.
Example Customer Table being sent to me:
Name AccountNo
----- -----------
abc A5071
def 57791
ghi 8W551
jkl 07A11 & 13866
mno 015X1, 0725A, 07551
Note there can be more than one leading zero in the accountNo. So I want my new table ("New_Cust_Table") to look like:
UserId Pwd SelectStmt
------ ------ -------------------------------
abc1 abc1# And AccountNo LIKE '%A5R7'
def1 def1# And AccountNo LIKE '%5779'
ghi1 ghi1# And AccountNo LIKE '%8W55'
jkl1 jkl1# And (AccountNo Like '%07A11' OR Account LIKE '%13866')
... etc.
Ignoring the Cust Names with multiple Account numbers for the moment, my SQL Looks like this:
-- DECLARE VARIABLES
DECLARE @UserID varchar(20)
DECLARE @UserPwd varchar(20)
DECLARE @SelectStmt varchar(200)
DECLARE NewCustUser CURSOR FOR
SELECT Name, AccountNo FROM Cust_Table
OPEN NewCustUser
FETCH NEXT FROM NewCustUser INTO @UserID @SelectStmt
WHILE (@@FETCH_STATUS = 0)
BEGIN
IF (LEN(@SelectStmt) <= 6) -- ACTUALLY GET MULTIPLE ACCOUNT Nos for ONE Customer
Begin
Print 'Account is ' +@SelectStmt+' for '+@UserID
SET @SelectStmt = 'AND AccountNo LIKE ''%'+@SelectStmt+''''
Print @SelectStmt
SET @Statement = N'INSERT INTO [dbo].[New_Cust_Table] VALUES ('''+@UserID+'1'','''+@UserID+'1#'','''+@SelectStmt+''')'
Print @Statement
EXEC sp_executesql @Statement
END
FETCH NEXT FROM NewCustUser INTO @UserID @SelectStmt
END
CLOSE NewCustUser
DEALLOCATE NewCustUser
Some of the error message I get:
- Incorrect syntax near ''.
- The name "A5R7" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
Perhaps there is a CAST, CONVERT or COLLATE is needed I have experimented with those and have not found anything that works just right yet...