I have a table, named FacilityDatabaseConnection, like-so, ID, FacilityID, DatabaseTypeID, ConnectionString
So given a FacilityID and DatabaseTypeID pair you'd get a ConnectionString. Both Facility and DatabaseType Tables have "Name" Fields. I would like to make a "Name" field in FacilityDatabaseConnection to do the following,
SELECT (dbo.Facility.Name+' - '+dbo.DatabaseType.Name) as Name
FROM dbo.FacilityDatabaseConnection
INNER JOIN dbo.Facility
ON dbo.FacilityDatabaseConnection.FacilityID = dbo.Facility.ID
INNER JOIN dbo.DatabaseType
ON dbo.FacilityDatabaseConnection.DatabaseTypeID = dbo.DatabaseType.ID
So that it returns "FacilityName - DatabaseType"
This works as a query but is it possible to make this a field?
I've tried,
ALTER TABLE dbo.FacilityDatabaseConnection
ADD Name AS (SELECT (dbo.Facility.Name+' - '+dbo.DatabaseType.Name) as Name
FROM dbo.FacilityDatabaseConnection
INNER JOIN dbo.Facility
ON dbo.FacilityDatabaseConnection.FacilityID = dbo.Facility.ID
INNER JOIN dbo.DatabaseType
ON dbo.FacilityDatabaseConnection.DatabaseTypeID = dbo.DatabaseType.ID) PERSISTED
Which gave me an error of "Subqueries are not allowed in this context. Only scalar expressions are allowed."
Is there a way to achieve this or is such a calculated field not possible?
Assuming this is SQL Server, computed columns cannot reference other tables, so what you are suggesting is not possible.
See also http://msdn.microsoft.com/en-us/library/ms191250%28v=sql.105%29.aspx
You should use a view/function/stored procedure instead.
There is a secret way to make computed column access another table.
That is to create a user-defined function that defines the field. The UDF can then access the other table.
The alter statement looks something like:
ALTER TABLE dbo.FacilityDatabaseConnection
ADD Name AS udf_getFacilityName(FacilityId);
You can do the following
SELECT
(SELECT count(*) FROM table1) as new_column_name,
col1,
col2
FROM
table2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.