2

I'm trying to create a stored procedure in SQL Server Management Studio where I can find any invoices in a table belonging to a certain Vendor with a certain status. For example I have Vendor 123456 from my VB application and I want to find if they have any invoices in my InvoiceTable where the status = B and return either a true or false value. This is what I have been trying so far:

ALTER PROCEDURE [dbo].[CheckStatus] 

@VendorNumber  char    
AS
BEGIN

Select distinct
CASE WHEN OrderStatus = 'B' and VendorNumber = @VendorNumber then 'true' else 'False' END as Status
from InvoiceTable

END 

Right now it always returns a singular "False" value, no matter if orderstatus = B and vendornumber = @vendornumber or not.

I'm not sure if this is possible or I'm even on the right page

7
  • 1
    Your query builds a list of 'true' or 'false' for all records in the table and then distincts it to 'true','false'. Apparently 'false' happens to be on the first row and your app never reads the second row.
    – GSerg
    Sep 22, 2015 at 17:55
  • I would move your case clauses into a where clause, select count from that and if your result > 0, then you know you have invoices. Your distinct is probably always going to return 2 rows: 'True' and 'False' and it probably just so happens that false is first
    – mafafu
    Sep 22, 2015 at 17:55
  • 1
    @MikeDavis My psychic powers tell me your = @VendorNumber is never true because you declared it as char.
    – GSerg
    Sep 22, 2015 at 18:06
  • 1
    @GSerg I declared it the same datatype as it is in my table
    – Mike Davis
    Sep 22, 2015 at 18:14
  • 1
    I'm pretty sure you have something like char(50) in the table @MikeDavis.
    – GSerg
    Sep 22, 2015 at 18:15

3 Answers 3

4

You can try with this

IF EXISTS(SELECT * 
    FROM InvoiceTable
    WHERE OrderStatus = 'B' and VendorNumber = @VendorNumber
    ) 
  SELECT 'True'
ELSE
  SELECT 'False'
0
0

I want to find if they have any invoices in my InvoiceTable where the status = B and return either a true or false value

IF (SELECT COUNT(*) 
    FROM InvoiceTable
    WHERE OrderStatus = 'B' and VendorNumber = @VendorNumber
    ) > 0
  SELECT 'True'
ELSE
  SELECT 'False'
1
  • 3
    Please never use count where you only need exists.
    – GSerg
    Sep 22, 2015 at 18:03
0
DECLARE @Result varchar(10)

IF EXISTS(SELECT * 
        FROM InvoiceTable
        WHERE OrderStatus = 'B' and VendorNumber = @VendorNumber
        ) 
BEGIN
      SET @Result = 'True'
END
ELSE BEGIN
      SET @Result = 'False'
END

RETURN @Result

Note - You can use bit instead of returning 'True' or 'False'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.