I realize it's been stated that the id doesn't have to be stable, but I don't see an answer providing a 'stable' version so I felt it was warranted.
A stable way to generate an id for a view is to create a SHA1 hash, whether it use a column (or columns) from within the view, or a runtime computation.
Generally, this is ideal to use since you can reliably come back to this ID over and over again. In some cases, it can even be used to know whether or not something has changed that's important for the business logic.
For example,
If you create a hash by concatenating the start & end dates CONCAT_WS('-', ...[<your_columns>])
of some appointment, save that hash elsewhere, then come back to query it and realize it no longer exists, then you know that there's been 1 (or more) updates since you've last queried this appointment.
To do this in SQL Server, you can use some built-in functions:
SELECT
HASHBYTES('SHA1', CAST(some_table.some_column as VARCHAR)) as id,
FROM
your_table
Though, since this function returns a varbinary(1)
, you may want to cast this to a proper string.
Here's how you would do that:
SELECT
master.dbo.fn_varbintohexstr(HASHBYTES('SHA1', CAST(some_table.some_column as VARCHAR))) as id,
FROM
your_table
Bear in mind, the master.dbo
portion is assuming some SQL Server naming conventions
And lastly, you'll notice that SQL Server infers the data type for this column as nvarchar(max)
, so if you want to reel this in, here' how you can do that:
SELECT
CAST(master.dbo.fn_varbintohexstr(HASHBYTES('SHA1', CAST(some_table.some_column as VARCHAR))) as varchar(42)) as id,
FROM
your_table
Note: This answer is known to work on SQL Server 2019 and up. Not to say it doesn't work on older versions, I just didn't check.