May 25, 2005 at 8:42 am
I have a store procedure and I am getting null value for one of my declare variable and I am trying to add that variable into my insert statement and it giving me null value error. Here is the procedure.
CREATE PROCEDURE [dbo].[Insert_Inspection]
@Receiving int
AS
Declare @LotNo varchar(50)
select @LotNo = [Lot No] from Receiving where [Receiving Log No] = @Receiving
Declare @PartId varchar(50)
Select @PartId = Max([Part ID]) + 1 from [Receiving Inspection Header] where [Receiving Log No] = @Receiving And [
“Need code to set @PartId =1 when it return Null”
SET NOCOUNT OFF;
INSERT INTO dbo.[Receiving Inspection Header] ([Receiving Log No], [Lot No], [Part Id]) VALUES (@Receiving, @LotNo, @PartId)
GO
For variable @PartId – There is no record present so the select statement for @PartId is giving my NULL value and if I try to use NULL into Insert statement it is giving me error. I would like to set @PartId = 1 when it return NULL from select statement. How can I do that?
May 25, 2005 at 8:52 am
Select @PartId = ISNULL(Max([Part ID]),0) + 1 from [Receiving Inspection Header] where [Receiving Log No] = @Receiving And [Lot No] = @LotNo
May 25, 2005 at 8:57 am
Or you could do this:
INSERT INTO dbo.[Receiving Inspection Header] ([Receiving Log No], [Lot No], [Part Id]) VALUES (@Receiving, @LotNo, ISNULL( @PartId,1) )
May 26, 2005 at 1:46 pm
Coalesce(@PartID, 1)
That'll give you 1 if it's null, and @PartID if it isn't.
May 26, 2005 at 2:14 pm
@PartId should probably be declared as an Int and not a VarChar
@PartId is not initialzed and therefore is null before the select:
If the select returns 0 rows then the @PartId will be unchanged and will remain null.
If the select does contain rows and the all values for Part_ID are null then @PartId will be assigned null.
After the select:
Set @PartId = IsNull( @PartId, 1 )
Whether the select returns a null or returns no rows, the Set IsNull will give the desired results.
May 29, 2005 at 9:47 pm
I like the coalesce. Nice and succinct, and from a newbie ?!
Added later: Whoops! Didn't mean to call you a newbie - just realised that Newbie refers to how many posts you've made.
May 31, 2005 at 7:30 am
LOL that's ok.
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply