如果在If语句中使用了值,则从存储过程返回值

时间:2018-10-19 10:06:10

标签: sql-server database stored-procedures

我有一个简单的MSSQL存储过程,该存储过程应查询表并返回一个值。

我在SELECT之后添加了IF语句,以执行匹配项。但是,此IF语句阻止返回@countrycode值。

所以我的问题是,如何在仍然执行IF操作的同时返回@countrycode值?

请随时提出一种更为优雅的方法。

BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE @countrycode VARCHAR(10)

-- Insert statements for procedure here
SELECT @countrycode = countrycode FROM tblIpLocation WHERE ipnumber = @ipnumber

-- Perform action if countrycode is found
IF @countrycode is null
    PRINT 'Nothing found'
ELSE 
    -- Increment the positivequerycount column in the same row from which the countrycode was made
    UPDATE tblIpLocation 
             SET positivequerycount = positivequerycount + 1 
             WHERE ipnumber = @ipnumber

END

1 个答案:

答案 0 :(得分:0)

感谢丹·古兹曼,你让我走上了正轨。

我尝试了以下操作以返回值...

SELECT @countrycode

但是,当然需要...

SELECT @countrycode AS countrycode

最终的解决方案是。

BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE @countrycode VARCHAR(10)

-- Insert statements for procedure here
SELECT @countrycode = countrycode FROM tblIpLocation WHERE ipnumber = @ipnumber


-- Perform action if countrycode is found
IF @countrycode is null
    PRINT 'Nothing found'
ELSE

    -- Increment the positivequerycount column in the same row from which the countrycode was made
    UPDATE tblIpLocation SET positivequerycount = positivequerycount + 1 WHERE ipnumber = @ipnumber

    SELECT @countrycode AS countrycode

END

感谢您的帮助