SQL确定参数是否具有不起作用的值

时间:2015-09-07 20:23:45

标签: sql sql-server

我如何使用IF语句来确定一个参数是否有值然后做一些工作,参数获取查询字符串但它返回任何记录。有人能指出我正确的方向吗?

CREATE PROCEDURE [dbo].[spAttachment_View]
    @knowid int,
    @actionid int   
AS
    if(@actionid is null)
    begin
        SELECT        
            name, contentType, uploadKnowledgeID AS id
        FROM            
            t_uploadFileForKnowledge
        WHERE        
            (knowledgeID_FK = @knowid)
    end
    else
    begin
       SELECT        
           name, contentType, uploadActionTicketID AS id
       FROM            
           [t_uploadForAction]
       WHERE        
           (actionID_FK = @actionid)
end

2 个答案:

答案 0 :(得分:1)

SQL Fiddle demo

这有效

CREATE PROCEDURE [dbo].[spAttachment_View]
    @knowid int,
    @actionid int   
AS
    if(@actionid is null)
    begin
        SELECT 'Im null'                       
    end
    else
    begin
       SELECT 'Im not null'
    end

EXEC [dbo].[spAttachment_View] @knowid =1 , @actionid = null

答案 1 :(得分:0)

您可以使用COALESCE获得更好的解决方案,而不是测试null,您可以在null的情况下提供默认(有效)值。否则请查看上面的Oropeza解决方案。