I have a SQL Server 2008 R2 database. This database has two tables called Pictures and PictureUse.
Picture table has the following columns:
Id (int)
PictureName (nvarchar(max))
CreateDate (datetime )
PictureUse table has the following columns :
Id (int)
Pictureid (int)
CreateDate (datetime )
I need to create a computed column in the Picture
table which tells me that how many times this picture has been clicked.any help ?
You can create a user-defined function for that:
The computed column can then be added like this:
However, I would rather make a view for this:
This will work
try this
A computed column may only reference other columns in the same table. You could (as per jeroenh's answer) use a UDF, but the column won't be stored or be indexable and so it has to be recomputed every time the row is accessed.
You could create an indexed view that contains this information (if, as I suspect, it's just the count of rows from
PictureUse
):Behind the scenes, SQL Server will effectively create a table that contains the results of this view, and every insert, update or delete to
PictureUse
will maintain this results table automatically for you.you dont have to add the computed column to your table, because, after its updated,if the original table data got changed, then data become inconsistent , you can always use this select statement to get the column count, or create it as a view