Question: This is a pretty straightforward error, but I can't figure out why I am getting it. I have one column selected in my declare (TABLE\_NAME) and am fetching into one variable (@cTableName). What gives?

```
CREATE PROCEDURE [dbo].[updateNumbers_ArchiveDB]
(
 @accountNumber varchar(50),
 @padding varchar(50),
 @proc_dateStart datetime,
 @proc_dateEnd datetime
 )
 AS

 DECLARE @cTableName varchar(50)

    DECLARE CursorYearlyTables CURSOR FOR
    SELECT  TABLE_NAME
    FROM  INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME like 'Archive[12]%' and len(TABLE_NAME) = 14
    ORDER BY TABLE_NAME;

-- =============================================
-- Open the cursor and iterate over the monthlies
-- =============================================
OPEN CursorYearlyTables 
fetch next from CursorYearlyTables into @cTableName
while (@@fetch_status <> -1)

 BEGIN
 SET NOCOUNT ON; 

declare @q varchar(1000);

set @q = 'Update' + @cTableName +
         'SET LogicalAccount = @padding + @accountNumber' +
         'WHERE ProcessDate BETWEEN CAST(@proc_dateStart AS DATE) AND CAST(@proc_dateEnd AS DATE)'
exec(@q)

fetch next from CursorYearlyTables into @cTableName

END

close CursorYearlyTables;
DEALLOCATE CursorYearlyTables;

```

Answer: 
Could you try it with these lines in the cursor

```
declare @q nvarchar(max);

set @q = 'Update ' + @cTableName +
         'SET LogicalAccount = '+@padding + @accountNumber +
         'WHERE ProcessDate BETWEEN CAST('''+CONVERT(VARCHAR(20),@proc_dateStart)+''' AS DATE) AND CAST('''+CONVERT(VARCHAR(20),@proc_dateEnd)+''' AS DATE)'

exec sp_executesql @q

```

to account for SQL\_Injection DavidG commented:

```
declare 
    @q nvarchar(max) = 'update '+@cTableName+' SET LogicalAccount = @a where ProcessDate BETWEEN CAST(@b AS DATE) AND CAST(@c AS DATE))',
    @param1 nvarchar(100) = @padding+ @accountNumber,
    @ParamDefinition nvarchar(500) = N'@a varchar(100), @b datetime, @c datetime'

exec sp_executesql @q, @ParamDefinition,@a = @param1,@b = @proc_dateStart, @cTableName = @proc_dateEnd

```
Please use `CONVERT` function

```
  CAST('''+CONVERT(VARCHAR(108),@proc_dateStart)+''' AS DATE) AND CAST('''+CONVERT(VARCHAR(108),@proc_dateEnd)+''' AS DATE)'

```