Click here to Skip to main content
15,886,664 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
All Time Show Null value
Please help me what is the wrong in my code

What I have tried:

declare @mxdbvlu  int
 declare @dbvlunm int
  set @mxdbvlu= (select max(Database_name) from TBL_FY_SELECT_1)
 if @mxdbvlu = null 
 set @dbvlunm=1000
 else 
 set @dbvlunm=sum(@mxdbvlu+1)
  select @dbvlunm,@mxdbvlu
Posted
Updated 12-Feb-19 6:41am

If I create a table with two columns: ID (int, Identity) and Database_name (NVARCHAR, MAX) and run your code, I do indeed get NULL, NULL.

But add two data rows:
SQL
ID      Database_name
1       AAAA      
2       AAAB
And I don't - I get an exception becuase it can't convert "AAAA" to an integer value.
If I replace the data with this:
SQL
ID      Database_name
1       1111      
2       1112
Then I get "reasonable" data:
(No column name) (No column name)
1113             1112
So your choice of column name is clearly wrong: you can't put a name in there.

And I can only replicate your failure when there are no rows - so start by checking your data.

But ... if you are using this to build a new database with sequential names each time you add some data, then that's probably a bad design. I'd strongly suggest that you rethink exactly why you decided this would be a good solution - both from a "why didn't I use an IDENTITY column?" POV, and a "why the heck do I need new databases at all, that's just silly" approach.
 
Share this answer
 
I can see two obvious issues with your code:
SQL
if @mxdbvlu = null 
If either or both operands are NULL, the comparison operators (=, !=) will return UNKNOWN. This is neither true nor false, so the If branch will not be executed.

To test whether a value is NULL, use Is Null instead:
IS NULL (Transact-SQL) - SQL Server | Microsoft Docs[^]
SQL and the Snare of Three-Valued Logic - Simple Talk[^]

SQL
set @dbvlunm=sum(@mxdbvlu+1)
Since you're not calculating an aggregate over a set of records, you don't need Sum(...) here. Just use:
SQL
set @dbvlunm = @mxdbvlu + 1
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900