I have a query with a select statement in a loop and at the same time I want to insert a varchar variable and selected value into a temporary table, but I get an error like:
Msg 207, Level 16, State 1, Line 2
Invalid column name 'SP419001_SID'
This SP419001_SID is the value contained in the varchar variable @dbName.
This is my query:
CREATE TABLE #tempCounter
(
dbName1 varchar(max),
counterNumber1 int
)
DECLARE
@counter INT = 1,
@max INT = 0,
@dbName VARCHAR(100),
@count INT = 0,
@SQLTEXT VARCHAR(MAX),
@counterNumber VARCHAR(10)
SELECT @max = COUNT(id) FROM #tempPnamePadd
WHILE @counter <= @max
BEGIN
SET @dbName='';
-- Do whatever you want with each row in your table variable filtering by the Id column
SELECT @dbName = name
FROM #tempPnamePadd
WHERE Id = @counter
PRINT @dbName
SET @SQLTEXT =
--SELECT distinct PN.NAME_FORMAT_CODE, NAME_BUSINESS, INDIVIDUAL_FIRST, A.ADDRESS_ID, A.ADDR_LINE_1, A.ADDR_LINE_2, A.ADDR_LINE_3, A.CITY, A.STATE
'DECLARE @dbn VARCHAR(200)
SET @dbn ='+ @dbName +';
INSERT INTO #tempCounter
(dbname1, counternumber1)
SELECT @dbn ,
(SELECT count(*)
FROM '+ @dbName +'.dbo.PRELA PR
INNER JOIN '+ @dbName +'.dbo.PNAME PN
ON PR.NAME_ID = PN.NAME_ID
INNER JOIN '+ @dbName +'.dbo.PNALK NK
ON PN.NAME_ID = NK.NAME_ID
INNER JOIN '+ @dbName +'.dbo.PADDR A
ON NK.ADDRESS_ID = A.ADDRESS_ID
WHERE (NAME_FORMAT_CODE=''B'' and NAME_BUSINESS like ''%BN'') OR
(NAME_FORMAT_CODE <> ''B'' and INDIVIDUAL_FIRST = ''John'') OR
(ADDR_LINE_1=''WELLS STREET'' AND CITY=''HOLLYWOOD'' AND STATE=''IA'')
)
'
--PRINT @SQLTEXT
EXEC (@SQLTEXT)
SET @counter = @counter + 1
END
SELECT @dbn ,you need quotes around the@dbnor it tries to select the db name as a column.