这是一个相当简单的错误,但我无法弄清楚为什么我会得到它。我在声明(TABLE_NAME)中选择了一列,并且正在获取一个变量(@cTableName)。是什么给了什么?
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;
答案 0 :(得分:2)
你可以用光标
中的这些行来试试吗?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
考虑到SQL_Injection,DavidG评论说:
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
答案 1 :(得分:0)
请使用CONVERT
功能
CAST('''+CONVERT(VARCHAR(108),@proc_dateStart)+''' AS DATE) AND CAST('''+CONVERT(VARCHAR(108),@proc_dateEnd)+''' AS DATE)'