SQL语句连接表是空查询

时间:2013-03-14 03:13:32

标签: sql join

您好我正在使用Join表查询来检索一些数据..

USE [AccountingSystem_TEST]
GO
/****** Object:  StoredProcedure [dbo].[spHRLeaveEntitlementBuildTemp]    Script Date: 03/14/2013 09:18:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER Procedure [dbo].[spHRLeaveEntitlementBuildTemp]
    (   
     @CreatedUserID as nvarchar(9)
    ,@EmployeeID nvarchar(9) 
    ,@EmpName nvarchar(150)
    )
AS
BEGIN

    Select A.CodeHRLeaveType,
        COALESCE(B.LeaveBalance) LeaveBalance           
    From HRLeaveType A
        LEFT JOIN HRLeaveMaster B 
        On A.CodeHRLeaveType = B.CodeHRLeaveType
    Where   B.EmployeeID = @EmployeeID

    Delete dbo.HrLeaveMasterTemp
    Where UserID = @CreatedUserID 

    INSERT INTO [dbo].[HrLeaveMasterTemp]
       ( [UserID]
        ,[EmployeeID] 
        ,[EmpName]
        ,[CodeHRLeaveType]
        ,[LeaveBalance]
        ,[Status] 
        )
    Select 
         @CreatedUserID             
        ,[EmployeeID]
        ,@EmpName
        ,[CodeHRLeaveType]
        ,[LeaveBalance]
        ,[Status]           
    From dbo.[HRLeaveMaster]
    Where EmployeeID =@EmployeeID
END
--Select * From HRLeaveMasterTemp

如果leavebalance为null,我需要表显示0 ..但语句显示错误..请帮帮我..

2 个答案:

答案 0 :(得分:1)

使用COALESCE

Select  A.CodeHRLeaveType,
        COALESCE(B.LeaveBalance) LeaveBalance           
From    HRLeaveType A
        LEFT JOIN HRLeaveMaster B 
            On A.CodeHRLeaveType = B.CodeHRLeaveType
Where   B.EmployeeID = @EmployeeID

答案 1 :(得分:1)

在Oracle中,null函数的替换与NVL函数一起使用。 在MySql中,null函数的替换与IFNULL函数一起使用。

请查看http://www.w3schools.com/sql/sql_isnull.asp。这对你有所帮助。

声明应该是 -

Select A.CodeHRLeaveType,
    IFNULL(B.LeaveBalance,0) LeaveBalance           
From HRLeaveType A
    LEFT JOIN HRLeaveMaster B 
    On A.CodeHRLeaveType = B.CodeHRLeaveType
Where   B.EmployeeID = @EmployeeID