Here is a simplified version of a stored procedure I am trying to write in SQL Server 2005.
My question is this:
I have declared a variable @docid to which I want to assign the results of a query as I Iterate through my cursor, if there is not an exact match, then I want to run another query and try for the next best match.
I tried putting in a test that says IF @docid IS NULL then BEGIN [second query]. This does not work since the variable @docid will not be Null it will just retain the previous value until the conditions for the first query are met and it is assigned a new value.
So how can I say “If I try to assign a docid to the variable @docid, but there is no match based on the conditions in the query then run the next query instead or set @docid=''"? Any help would be appreciated. Thanks
declare @docid bigint,
@account varchar(30)
While @@fetch_status=0
BEGIN
Select @Docid=Docid
FROM printdata
WHERE Account=@account
IF @docid Is Null --Docid Is never Null once assigned a value
BEGIN
Select @Docid=Docid
FROM printdata
WHERE balance=@balance
END
Well, I would just first initialize
@docidto NULL – then it will be NULL if nothing is found: