如何在存储过程中检查该值是否为空?

时间:2014-03-12 10:35:57

标签: sql sql-server stored-procedures

SQL Server Management Studio,存储过程

我从Visual Studio传递customerName,在存储过程中我希望得到customerID

现在我想检查customerId是否为空,这意味着这是一个新客户。如果是这样,我想在表中插入该客户。然后我想获取客户ID,并希望存储在TableB

以下是示例代码:

还告诉如何执行

if(@customerId == null)
{
   Insert customerDetails into CustomerTable;
   get CustomerId.
} //General workflow what i want.

为此,我编写了一个SQL Server存储过程

create procedure Customers_AddData2    
    @CustomerName nvarchar(50) = null
As     
   --Get Customer ID
   declare @CustomerID numeric(18, 0)= (SELECT distinct [CustomerID] FROM [tblCustomerMaster] WHERE CustomerName = @CustomerName)

  --checking if customerId not found
  -- Here is some error, Not getting syntax 

  IF(@CustomerID IS NULL == true)  
  {
      INSERT INTO [tblCustomerMaster] ([CustomerName]) 
      VALUES (CustomerName)
  }

  -- Now get customer id
  @CustomerID numeric(18, 0)= (SELECT distinct [CustomerID] FROM [tblCustomerMaster] WHERE CustomerName = @CustomerName)

2 个答案:

答案 0 :(得分:5)

只需IF(@CustomerID IS NULL)就够了

IF(@CustomerID IS NULL)
BEGIN
     --insert here..
      INSERT INTO [tblCustomerMaster]
     ([CustomerName]

    VALUES

    (CustomerName)
    SET @CustomerID = Scope_Identity() -- sql server syntax to get the ID after insert..
END 
ELSE
BEGIN
   -- update perhaps..
END

答案 1 :(得分:0)

您可以尝试这样:

if (isnull(@customerID) == 1)
BEGIN
     --Your code
END 
ELSE
BEGIN
   -- code
END

同时更改此行

declare @CustomerID numeric(18,0)= (SELECT distinct [CustomerID] FROM   [tblCustomerMaster]     where CustomerName = @CustomerName)

用这个:

declare @CustomerID numeric(18,0)
(SELECT @CustomerID := [CustomerID] 
 FROM   [tblCustomerMaster]     
where CustomerName = @CustomerName)