So I got a problem looks like with string conversion. I have tried everything under the sun. My goal is to inert the values from the loop into the table. However I can get the field value but I can not get the table name value due to sql thinks I am calling a table rather than a string. I have tried casting converting everything. Here is the code sample:
DECLARE @C varchar(65)
DECLARE @FieldName varchar(50)
SET @FieldName = 'ProjectID'
SELECT @C = MIN(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'Base Table'
CREATE TABLE #temp_t (
[field] varchar(100),
[tblname] varchar(100)
)
WHILE @C is not null
BEGIN
DECLARE @qbExists int
DECLARE @tblname varchar(100)
SET @tblname = CONVERT(varchar(100), @C)
SELECT @qbExists = COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @C AND COLUMN_NAME = @FieldName
IF @qbExists = 1 AND
@C <> 'TimeExpenseUnionQuery' AND
@C <> 'TimeExpense' AND
@C <> 'BC_BA' AND
@C <> 'BC_BE' AND
@C <> 'BC_EL' AND
@C <> 'BC_TE'
BEGIN
EXEC('
SELECT ' + @FieldName + ', ' + @C + ' FROM ' + @tblName +'
')
END
SELECT @C = MIN( TABLE_NAME ) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME > @C
END
SELECT * FROM #temp_t
DROP TABLE #temp_t
The problem child lies within the SELECT ‘ + @FieldName + ‘, ‘ + @C + ‘ FROM ‘ + @tblName.
Now if I do not use the @C it works fine. If I try to CONVERT or CAST the @C I get an invalid column name? What gives?
You need to quote it to make it a constant, which requires doubling up because of dynamic SQL
Whether the use of dynamic SQL is a good idea or not is a different matter…