动态sql无法按预期工作

时间:2016-06-23 10:24:35

标签: sql sql-server

我试图动态找不到parentsku产品,但我无法调试错误。我试图将结果插入到全局临时表中,但它没有按预期工作

CREATE PROC dbo.spa_IQR_Report
( 
@ReportType VARCHAR(100),           
@db_name VARCHAR(100) = '',                        
@TableName VARCHAR(1000) = '', 
@SKU NVARCHAR(1000)  = '',                                                                   
@PartNo NVARCHAR(1000) = '',                       
@column_name VARCHAR(1000) = '' ,                  
@product_name NVARCHAR(1000) = '',                 

@category VARCHAR(1000) = '',                    
@sub_category VARCHAR(1000) = '',                  
@description VARCHAR(1000) = '',

@Category_tbl  VARCHAR(1000) = '',
@CategoryId_column VARCHAR(1000) = '',
@Category_name_column VARCHAR(1000) = '',

@RowOperator VARCHAR(10) = '>'


)
AS
BEGIN

IF @ReportType = 'ParentSKU_Products' 
        BEGIN

            IF OBJECT_ID ('tempdb..##ParentSKU_Products') IS NOT NULL
            DROP TABLE ##ParentSKU_Products

            DECLARE @SQL NVARCHAR(MAX); 
            SET @SQL = 'SELECT DISTINCT * INTO ##ParentSKU_Products FROM ['+@TableName+']';
            PRINT(@SQL)
            EXEC(@SQL)   

            SELECT *FROM ##ParentSKU_Products
        END

IF @ReportType = 'ParentChild_Products' 
BEGIN

        IF OBJECT_ID('tempdb..##TEMP_ParentsChild_Products') IS NOT NULL
        DROP TABLE ##TEMP_ParentsChild_Products


        SET @SQL = 'SELECT 
        a.'+@PartNo+' AS ''Parent SKU''
        ,COUNT('+@SKU+') AS ''ChildSKU_Total''
        ,STUFF((SELECT '','' +'+@SKU+'
                   FROM ['+@TableName+'] b 
                   WHERE b.'+@PartNo+' = a.'+@PartNo+' 
                  FOR XML PATH('''')),1, 1, '''') AS ''ChildSKU''
        INTO ##TEMP_ParentsChild_Products
        FROM ['+@TableName+'] a
        GROUP BY '+@PartNo+'';

        PRINT(@SQL) 
        EXEC(@SQL) 



END

END

    EXEC spa_IQR_Report 
    @ReportType ='ParentSKU_Products',                        
    @db_name  = '',                        
    @TableName ='core data', 
    @SKU='' ,                                                                    
    @PartNo='',                       
    @column_name='' ,                     
    @product_name ='',               

    @category='' ,                    
    @sub_category ='',                   
    @description='' ,

    @Category_tbl=''  ,
    @CategoryId_column ='',
    @Category_name_column='',
    @RowOperator=''

以下是我收到的错误消息:

"Incorrect syntax near the keyword 'as'.
Msg 1038, Level 15, State 4, Line 1
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.
Msg 1038, Level 15, State 4, Line 1"

0 个答案:

没有答案