首先,我对动态 SQL 没有任何经验,这是我的第一次尝试。我正在查看这里的答案,但各种纠正此问题的尝试都失败了,这让我更加困惑。
我创建了一个带有循环月份 [#Month] 的表,还创建了一个事务代码表 [#Tran_codes],我需要将这些与事务数据结合起来,但我收到了无效的对象名称“#Trans1”。我知道这是由于临时表超出范围,但我不知道如何修复它。
这是给我带来问题的代码,请您帮忙纠正或建议我在哪里可以阅读正确的语法以使用?
-------------------------------------------------------------------
PRINT '03. Create a Table with all Tran codes as per "02", with transaction amounts, per month-end date for past 25 months as set out by "01" '
-------------------------------------------------------------------
DECLARE
@i INT
,@j INT
,@Monthend_Date varchar(50)
,@Month_String VARCHAR(6)
,@SQL VARCHAR(MAX)
SET @i = 1
SET @j = (SELECT MAX(RowNum) FROM #Month)
WHILE @i <= @j
BEGIN
SET @Month_String = (SELECT MonthString FROM #Month WHERE RowNum = @i)
IF @i = 1
BEGIN
----------------------------------------------------------
SET @SQL = '
IF OBJECT_ID(''tempdb..#Trans1'') IS NOT NULL DROP TABLE #Trans
CREATE TABLE #Trans1
WITH
(
DISTRIBUTION = HASH(Tran_Date_Key)
,LOCATION = USER_DB
)
AS
SELECT
Monthend_Date = ''' + CONVERT(Varchar(30), @Monthend_Date) + '''
,Trans.Tran_Code_Key
,TD.Tran_Code
,TD.Description
,Amount
FROM DATASTORE_MIS.[dbo].vwF_Transaction_'+ @Month_String +' Trans
inner join DATASTORE_MIS.[dbo].vwF_Transaction_Description_'+ @Month_String +' as TD on Trans.Journal_No = TD.Journal_No
AND Trans.[Tran_Date_Key] = TD.[Tran_Date_Key]
'
EXEC (@SQL)
End
ELSE
BEGIN
SET @SQL = '
INSERT INTO #Trans1
SELECT
Monthend_Date = ''' + CONVERT(Varchar(30), @Monthend_Date) + '''
,Trans.Tran_Code_Key
,TD.Tran_Code
,TD.Description
,Amount
FROM DATASTORE_MIS.[dbo].vwF_Transaction_'+ @Month_String +' Trans
inner join DATASTORE_MIS.[dbo].vwF_Transaction_Description_'+ @Month_String +' as TD on Trans.Journal_No = TD.Journal_No
AND Trans.[Tran_Date_Key] = TD.[Tran_Date_Key]
'
EXEC (@SQL)
END
SET @i = @i + 1
END