如何使用动态SQL解决错误

时间:2019-06-18 09:08:13

标签: sql dynamic

执行存储过程时,收到以下错误消息。

消息245,级别16,状态1,过程USP_History_Building,第35行[批处理开始第8行] 将nvarchar值'SELECT * FROM EDB_Q217.dbo.POSTAL_ADDRESS PA WHERE PA.BUILDING_ID ='转换为数据类型int时,转换失败。

我尝试对代码稍作更改,但没有任何效果。

ALTER PROCEDURE [dbo].[USP_History_Building] 

     @BUILDING int

AS 

DECLARE @quarterStart int = 2
DECLARE @quarterEnd int = 1
DECLARE @yearStart int = 17
DECLARE @yearEnd int = 19
DECLARE @BUILDING_ID int
DECLARE @year int
DECLARE @quarter int

DECLARE @quarterForDbName nvarchar(4)
DECLARE @sqlStatement nvarchar(max)

SET @year = @yearStart
SET @quarter = @quarterStart
SET @sqlStatement = ''
SET  @BUILDING_ID = @BUILDING


WHILE @year <= @yearEnd
BEGIN
WHILE ((@year < @yearEnd AND @quarter <= 4) OR (@year = @yearEnd AND 
@quarter <= @quarterEnd))

BEGIN
SET @quarterForDbName = 'Q' + CAST(@quarter AS nvarchar(1)) + 
CAST(@year AS nvarchar(2))

    SET @sqlStatement = @sqlStatement + 
    'SELECT * FROM EDB_'+ @quarterForDbName +'.dbo.POSTAL_ADDRESS PA 
    WHERE PA.BUILDING_ID = ' + @BUILDING_ID


  SET @quarter = @quarter + 1  


   END

SET @quarter = 1
SET @year = @year + 1

END

PRINT @sqlStatement
EXEC (@sqlStatement)

预期结果是,前8个季度返回了许多地址字段。

1 个答案:

答案 0 :(得分:0)

使用sp_executesql将参数传递给代码:

WHILE @year <= @yearEnd
BEGIN
    WHILE ((@year < @yearEnd AND @quarter <= 4) OR (@year = @yearEnd AND @quarter <= @quarterEnd))
    BEGIN
        SET @quarterForDbName = 'Q' + CAST(@quarter AS nvarchar(1)) + CAST(@year AS nvarchar(2));

        SET @sqlStatement = @sqlStatement + '
SELECT *
FROM EDB_'+ @quarterForDbName +'.dbo.POSTAL_ADDRESS PA 
WHERE PA.BUILDING_ID = @BUILDING_ID
';
        SET @quarter = @quarter + 1 ; 
    END;
    SET @quarter = 1;
    SET @year = @year + 1;
END;
PRINT @sqlStatement
EXEC sp_executesql @sqlStatement,
                   N'@BuildingId int',
                   @BuildingId=@BuildingId;

您不能将表名作为参数传递,但应使用参数传递常量值。