调用存储过程未知对象类型时遇到此问题

时间:2019-05-07 21:29:25

标签: sql-server tsql stored-procedures

我正在尝试编写一个需要调用存储过程的查询。但这总是会引发错误:

  

在CREATE,DROP或ALTER语句中使用的未知对象类型'TABLEIXICHistoricalData'。

这是查询:

USE ETLCourse

DECLARE @LOOP TABLE 
              (
                  ID INT IDENTITY(1,1),
                  TableName NVARCHAR(100)
              )

INSERT INTO @LOOP (TableName)
    SELECT TABLE_NAME
    FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_NAME LIKE '%_Stocks%'

DECLARE @b INT = 1, @m INT, @t NVARCHAR(100)

SELECT @m = MAX(ID) FROM @LOOP

WHILE @b <= @m
BEGIN
    SELECT @t = TableName 
    FROM @LOOP 
    WHERE ID = @b

    EXECUTE [dbo].[stp_BuildNormalizedTable] @t

    SET @b = @b + 1
END

这是步骤:

ALTER PROCEDURE [dbo].[stp_BuildNormalizedTable]
    @table NVARCHAR(100)
AS
BEGIN
    DECLARE @cleanTable NVARCHAR(100),
            @s NVARCHAR(MAX)

    SET @cleanTable = REPLACE(@table, '_Stocks', 'HistoricalData')

    SET @s = 'CREATE TABLE' + @cleanTable + '(ID INT IDENTITY(1,1), Price DECIMAL(13, 4), PriceDate DATE)
              INSERT INTO' + @cleanTable + '(Price,PriceDate) SELECT [Adj Close],[Date] FROM'
              + @table + ' ORDER BY Date ASC'

    --PRINT @s
    EXECUTE sp_executesql @s
END

它应该复制两个特定的列并使用@Loop表和过程创建一个新表

1 个答案:

答案 0 :(得分:3)

您需要在“创建表格”,“插入到”和“从”之后添加“空格”

declare @s nvarchar(max)
declare @cleantable nvarchar(100)
declare @table nvarchar(100)
set @cleantable = 'aaa'
set @table = 'bbb'

SET @s = 'CREATE TABLE' + @cleanTable + '(ID INT IDENTITY(1,1),Price Decimal(13,4),PriceDate DATE)
Insert into' + @cleanTable
+ '(Price,PriceDate) SELECT [Adj Close],[Date] FROM'
+ @table + ' ORDER BY Date ASC'

print @s

输出:

CREATE TABLEaaa(ID INT IDENTITY(1,1),Price Decimal(13,4),PriceDate DATE)
Insert intoaaa(Price,PriceDate) SELECT [Adj Close],[Date] FROMbbb ORDER BY Date ASC

使用“打印”检查您的查询。