在sql中使用查询的if语句

在sql中使用查询的if语句,sql,sql-server,stored-procedures,if-statement,sql-server-2000,Sql,Sql Server,Stored Procedures,If Statement,Sql Server 2000,我想问一下如何使用SQL中的IF语句执行条件检查,类似下面的示例 if (select* from table where id = @id) = 1 --if this returns a value insert statement else update statement go 或者类似的东西,比如使用存储过程 if (exec SP_something 2012, 1) = 0 insert statement else update stement 或者在sql

我想问一下如何使用
SQL
中的
IF语句执行条件检查,类似下面的示例

if (select* from table where id = @id) = 1 --if this returns a value

insert statement


else

update statement

go
或者类似的东西,比如使用存储过程

if (exec SP_something 2012, 1) = 0 

insert statement

else

update stement
或者在sql语句中使用UDF,如

if (select dbo.udfSomething(1,1,2012)) = 0 

insert statement

else

update statement

go

您将需要执行以下操作:

IF (SELECT COUNT(*) FROM Table WHERE ID = @id) = 1
BEGIN
    UPDATE Table SET Name = 'Name' WHERE ID = @id
END
ELSE
BEGIN
    INSERT INTO Table (Name) VALUES ('Name');
END
(1)使用语句块

IF 
(SELECT COUNT(*) FROM Production.Product WHERE Name LIKE 'Touring-3000%' ) > 5
BEGIN
   PRINT 'There are 5 Touring-3000 bikes.'
END
ELSE 
BEGIN
   PRINT 'There are Less than 5 Touring-3000 bikes.'
END ;
(2)调用存储过程。

DECLARE @compareprice money, @cost money 
EXECUTE Production.uspGetList '%Bikes%', 700, 
    @compareprice OUT, 
    @cost OUTPUT
IF @cost <= @compareprice 
BEGIN
    PRINT 'These products can be purchased for less than 
    $'+RTRIM(CAST(@compareprice AS varchar(20)))+'.'
END
ELSE
    PRINT 'The prices for all products in this category exceed 
    $'+ RTRIM(CAST(@compareprice AS varchar(20)))+'.'
声明@compareprice money,@cost money
执行Production.uspGetList“%Bikes%”,700,
@比较一下价格,
@成本产出

IF@cost以下示例将帮助您使用
IF-ELSE

CREATE PROCEDURE SetEngineerStock

    @EngineerId INT,
    @PartNumber CHAR(8),
    @NewUnitsHeld DECIMAL(6,2)
AS

BEGIN

    SET NOCOUNT ON;

    -- Does stock entry exist?
    IF EXISTS(SELECT * FROM EngineerStock
              WHERE EngineerId = @EngineerId AND PartNumber = @PartNumber)

        -- Yes, update existing row
        UPDATE EngineerStock
        SET UnitsHeld = @NewUnitsHeld
        WHERE EngineerId = @EngineerId AND PartNumber = @PartNumber

    ELSE

        -- No, insert new row
        INSERT INTO EngineerStock
        VALUES(@EngineerId, @PartNumber, @NewUnitsHeld)

END

@MuhammadHani先生,存储过程应该返回一个值,对吗?嗯,它被宣布为输出?输出和输出正确的2个参数sir?