Been struggling with this one for a good while now. I'm trying to use sp_executesql
below:
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
DECLARE @IntVariable int;
DECLARE @fulldbtablename nvarchar(500);
DECLARE @ID bigint;
SET @fulldbtablename = QUOTENAME(@databasename) + '.[DBO].' + QUOTENAME(@tablename)
SET @SQLString = N'SELECT TOP 1 @IDOut = ID FROM' + @fulldbtablename + 'WHERE LastModified < DATEADD(DAY, @daystokeep, GETDATE()) order by 1 desc';
SET @ParmDefinition = N'@daystokeep int,
@IDOut bigint OUTPUT';
SET @IntVariable = -1;
EXECUTE sp_executesql
@SQLString
,@ParmDefinition
,@daystokeep = @IntVariable
,@IDOut = @ID OUTPUT;
I'm getting the error Must declare the scalar variable "@ID"
I've reviewed the help below, but I can't shake this error. Has anyone any ideas? I am declaring @ID in DECLARE @ID bigint;
To help me debug, I split the query into a new window and ran the query below which completes successfully so I am pulling my hair out:
DECLARE @Databasename varchar(500)
DECLARE @Tablename varchar(500)
DECLARE @ID bigint;
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
DECLARE @IntVariable int;
DECLARE @fulldbtablename nvarchar(500);
SET @databasename = 'DatabaseName'
Set @Tablename = 'TableName'
SET @fulldbtablename = QUOTENAME(@databasename) + '.[DBO].' + QUOTENAME(@tablename)
SET @SQLString = N'SELECT TOP 1 @IDOut = ID FROM' + @fulldbtablename + 'WHERE LastModified < DATEADD(DAY, @daystokeep, GETDATE()) order by 1 desc';
SET @ParmDefinition = N'@daystokeep int,
@IDOut bigint OUTPUT';
SET @IntVariable = -1;
EXECUTE sp_executesql
@SQLString
,@ParmDefinition
,@daystokeep = @IntVariable
,@IDOut = @ID OUTPUT;
SELECT @ID
Anyone any ideas?????? Thank you!
sp_executesql
with anOUTPUT
variable? learn.microsoft.com/en-us/sql/relational-databases/…QUOTENAME(@tablename)
at the very least. You could also add checks to make sure@tablename
exists, prefix it with the right schema, etc. I wrote a two-part tip on SQL injection here and here.