I've been working on the code below. I'm trying to insert results of a declared variable into a sql statement. I've highlighted the section below that I'm talking about. What am I doing wrong here? I've tried a few different things. Do I need to create a temp table and import from the temp table to the live table?
Thank you for you time and help.
DECLARE @counter INT
,@dimtablename NVARCHAR(50)
,@dimKey INT
,@processdatekey INT
,@DimCount INT
,@sqlstmt VARCHAR(8000)
WHILE @counter <= (
SELECT MAX(DimKey)
FROM dbo.audit_HostDimensionName(NOLOCK)
)
BEGIN
SET @dimtablename = (
SELECT DimName
FROM dbo.audit_HostDimensionName WITH (NOLOCK)
WHERE DimKey = @counter
);
SET @dimkey = (
SELECT DimKey
FROM dbo.audit_JHostDimensionName WITH (NOLOCK)
WHERE DimKey = @counter
);
SET @processdatekey = (
SELECT cast(convert(VARCHAR, dateadd(d, - 1, getdate()), 112) AS INT) AS datekey
);
SET @DimCount = '(SELECT COUNT(*) from''' + @dimtablename + ''' with(nolock)) ';
SET @sqlstmt = 'INSERT INTO dbo.Audit_HostDimensionTracking(DateKey, DimKey, Row_Count) VALUES (''' + @processdatekey + ',' + @dimkey + ',' + @DimCount + ')'''
PRINT @sqlstmt
EXEC (@sqlstmt)
SET @counter = @counter + 1
END
@counter
– Martin Smith 7 hours agoQUOTENAME()
is far safer than manually adding square brackets yourself. – Aaron Bertrand♦ 6 hours ago