如何在SQL Server中执行此ORACLE语句?

时间:2011-04-24 23:16:19

标签: sql-server sql-server-2008

SELECT COUNT(Field1_) 
           FROM 
           (
               SELECT Field1_
               FROM Table1_
               WHERE Field1_= @Field1
           UNION ALL
               SELECT Field1_
               FROM Table2_
               WHERE DeliveryPoint_ = @Field1
           UNION ALL
               SELECT Table3_
               FROM GasSupplied_
               WHERE DeliveryPoint_ = @Field1
           UNION ALL
               SELECT Table4_
               FROM Gnsnominations_
               WHERE DeliveryPoint_ = @Field1
           UNION ALL
               SELECT Table5_
               FROM HourlyProfileReports_
               WHERE DeliveryPoint_ = @Field1
           )

我的代码有问题。请帮帮我。

DECLARE
              CountedRows NUMBER;
            BEGIN
              SELECT COUNT(*) INTO CountedRows 
              FROM Profiles_ 
              WHERE Field1_ = @Param1 AND RowNum < 2;  
                IF(CountedRows > 0)
                THEN
                    UPDATE Profiles_ 
                    SET 
                        Field2_ = @Param2,
                        Field3_ = @Param3,
            Field4_ = @Param4 
                        WHERE Field1_ = @Param1;
                ELSE
                INSERT INTO Profiles_
                (
                    Field1_, 
                    Field2_,
                    Field3_,
                    Field4_
                ) 
                VALUES
                (
                    @Param1, 
                    @Param2,
                    @Param3,
                    @Param4                    );
                END IF;
              END;

请帮帮我。我读了很多书和教程,但我无法理解。

2 个答案:

答案 0 :(得分:2)

您的第一个需要表别名

SELECT COUNT(Field1_) 
           FROM 
           (
               SELECT Field1_
               <snip>
               WHERE DeliveryPoint_ = @Field1
           ) AS foo

你的第二个应该开始

            DECLARE CountedRows int;


              SELECT CountedRows = COUNT(*) 
              FROM Profiles_ 
              WHERE Field1_ = @Param1 AND RowNum < 2;  

在语法上是正确的。同样使用END;而不是END IF;但是它会为您提供潜在的竞争条件。正如您在SQL Server 2008上一样,您应该考虑MERGE进行此类UPSERT

据我所知,第二个整体可以替换为。

MERGE INTO Profiles_
USING (VALUES(@Param1_) )T(P1)
ON Field1_ = P1
WHEN MATCHED THEN
  UPDATE SET Field2_ = @Param2_,
             Field3_ = @Param3_,
             Field4_ = @Param4_
WHEN NOT MATCHED BY TARGET THEN
  INSERT
  VALUES (P1, @Param2_, @Param3_, @Param4_);  

答案 1 :(得分:0)

设置命令优先于select命令。所以,你应该向select命令致敬并将其编码为

set countedRows = (SELECT COUNT(*) FROM Profiles_ );