Manaully generating your own Id int value

If you ever find yourself adding a row to a table that has a primary key int field that is not set as an Identity column, meaning it won’t create an Id for itself on inserts, then you need to insert your own Id value.

Of course the database should be responsible for this and the database should be fixed, but assuming you don’t have the authority to fix the database, and you are stuck working with a poorly designed table and you must insert a row, and to insert that row you must generate your own int Id value that is 1 greater than the Max Id, here is what the insert will look like:

Insert into MyBadlyDesignedTable (Id, Name ,ExpirationDate, Position)
values
(
  (select  MAX(Id) + 1  from MyBadlyDesignedTable)
  , 'Bob' 
  ,'1/15/2015'
  ,1
)

Or if you want to return the new ID you can do this:

Declare @newId int
select @newId = MAX(Id) +1  from MyBadlyDesignedTable

Insert into MyBadlyDesignedTable (Id, Name ,ExpirationDate, Position)
values
(
  @newId
  , 'Bob' 
  ,'1/15/2015'
  ,1
)

Select @newId

If you can fix your database, then do it. But if you can’t because it is a legacy system, then this will work*.

* I do worry that the a race condition may cause this fail if 2 inserts try to use the same key because they run their ‘select Max’ at the exact same time. If you know a better/safer way to do this, please leave a comment.

Recursive SQL Queries using Common Table Expressions

I often work with tables that will have a parent ID that relates to another row within the same table so that I can create a hierarchical relationship within table (a tree). When trying to display this tree I have usually relied a combination of code and calls to the database to get the nodes at each level based on the shared parent ID, however the other day I was in a situation that really needed to retrieve the entire tree with a single query.

Here is the method I found to retrieve an entire tree with a single call. This uses a common table expression. The first select statement will retrieve the initial return set which will be all items at the root (items with no parent), and then the second select statement recursively builds on that set using a UNION ALL and an inner join. In this case, I’m replacing the Name at each level with a concatenated string of ‘Parent Name : Child Name’.

with CTE as
(SELECT c.Id,c.AccountId,c.ParentId,c.Description,c.SortOrder,c.Active, CAST( c.Name as nvarchar(max)) as Name
FROM Context c
WHERE c.AccountId = @accountId
and ParentId = 0
and c.Active = ‘true’

UNION ALL

SELECT childContext.Id,childContext.AccountId,childContext.ParentId,childContext.Description,childContext.SortOrder,childContext.Active, CAST( CTE.Name + ‘ : ‘ + childContext.Name as nvarchar(max)) as Name
FROM Context childContext
JOIN CTE
ON childContext.ParentId = CTE.Id
Where childContext.Active = ‘true’

)

Select * from CTE
order by Name
END