如何使用动态SQL条件

时间:2011-10-04 12:01:29

标签: sql

我想把if条件放在后面查询但是得到错误

ALTER PROCEDURE [dbo].[GetExternalDocumentHistory]
    @reoid                  int, 
    @spType                 VARCHAR(50),
    @maximumRows            INT             = 0,
    @startRowIndex          INT             = 0,  
    @recordCount            INT  OUTPUT    
AS BEGIN

DECLARE @data TABLE(
        id                  INT IDENTITY(1,1),
        property_address    NVARCHAR(250),
        property_id         INT )

INSERT @data( property_address, property_id )

IF( @spType = 'ED' )
BEGIN
  SELECT property_address,  property_id 
  FROM external_documents_history as edu      
  WHERE edu.property_id = @reoid
END;

IF (@spType = 'GD'  ) 
BEGIN
   SELECT property_address, property_id 
   FROM external_documents_history as edu 
   WHERE edu.page_type = 'GD'
END;

SELECT @recordCount = COUNT(*) FROM @data
IF @maximumRows = 0     
BEGIN
   SET @startRowIndex = 0
   SET @maximumRows   = @recordCount
END

SELECT * FROM @data
WHERE id BETWEEN @startRowIndex + 1 AND @startRowIndex + @maximumRows
ORDER BY id  

END;

上述查询有什么问题?

5 个答案:

答案 0 :(得分:2)

INSERT语句后不能使用IF,最简单的选择是重写所有可能条件的插入;

IF (@spType = 'ED') BEGIN
  INSERT @data(property_address, property_id)
  SELECT property_address, property_id FROM external_documents_history as edu WHERE edu.property_id = @reoid
END

您也可以跳过SELECT @recordCount = COUNT(*) FROM @data并使用@@ROWCOUNT

答案 1 :(得分:2)

在where子句中使用case语句,例如

DECLARE @data TABLE(
        id                  INT IDENTITY(1,1),
        property_address    NVARCHAR(250),
        property_id         INT )

INSERT INTO @data( property_address, property_id )
select property_address,  property_id FROM external_documents_history as edu
    where
        case when @spType = 'ED' and edu.property_id = @reoid then 1
        case when @spType = 'GD' and edu.page_type = 'GD' then 1
        else 0
    end = 1
;

SELECT @recordCount = COUNT(*) FROM @data

     IF @maximumRows = 0 
         BEGIN
            SET @startRowIndex = 0
            SET @maximumRows   = @recordCount
         END

     SELECT * FROM @data
     WHERE id BETWEEN @startRowIndex + 1 AND @startRowIndex + @maximumRows
     ORDER BY id     
END;

答案 2 :(得分:2)

除了@Alex的两个条件INSERT(我认为最好的方式),这里是@Sorpigals答案的变体,没有CASE ::

  INSERT INTO @data( property_address, property_id )
    SELECT property_address
        ,  property_id 
    FROM external_documents_history as edu  
    WHERE ( @spType = 'ED' AND edu.property_id = @reoid )
       OR ( @spType = 'GD' AND edu.page_type = 'GD' )

答案 3 :(得分:1)

首先,这是不正确的:

INSERT @data( property_address, property_id )

应该是:

INSERT INTO table_name VALUES (value1, value2, value3,...)

并且这是在你的if语句之前,这可能是你的查询分析器/管理工作室抱怨if的原因。

答案 4 :(得分:1)

如果您正在尝试动态INSERT INTO表SELECT A,B,C FROM OtherTableDynamically,您将需要准备整个语句并使用sp_executesql。