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 ?
While you can't reference another table's column directly within your expression, you can invoke a user-defined function. And therefore, you could create a user-defined function that performs the calculation you need, then simply call that function as your computed column's expression.
To add a new computed columnRight-click Columns and select New Column. Enter the column name and accept the default data type (nchar(10)). The Database Engine determines the data type of the computed column by applying the rules of data type precedence to the expressions specified in the formula.
Some Limitations. You can not reference columns from other tables for a computed column expression directly. You can not apply insert or update statements on computed columns.
Click the tab for the table with the columns you want to copy and select those columns. From the Edit menu, click Copy. Click the tab for the table into which you want to copy the columns. Select the column you want to follow the inserted columns and, from the Edit menu, click Paste.
You can create a user-defined function for that:
CREATE FUNCTION dbo.CountUses(@pictureId INT)
RETURNS INT
AS
BEGIN
RETURN
(SELECT Count(id)
FROM PictureUse
WHERE PictureId = @PictureId)
END
The computed column can then be added like this:
ALTER TABLE dbo.Picture
ADD NofUses AS dbo.CountUses(Id)
However, I would rather make a view for this:
CREATE VIEW PictureView
AS
SELECT Picture.Id,
PictureName,
Picture.CreateDate,
Count(PictureUse.Id) NofUses
FROM Picture
JOIN PictureUse
ON Picture.Id = PictureUse.PictureId
GROUP BY Picture.Id,
PictureName,
Picture.CreateDate
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
):
CREATE VIEW dbo.PictureStats
WITH SCHEMABINDING
AS
SELECT PictureID,COUNT_BIG(*) as Cnt from dbo.PictureUse
GO
CREATE UNIQUE CLUSTERED INDEX IC_PictureStats on dbo.PictureStats (PictureID)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With