简体   繁体   English

计算字段,基于2个ID的SELECT

[英]Calculated field, SELECT based on 2 IDs

I have a table, named FacilityDatabaseConnection, like-so, ID, FacilityID, DatabaseTypeID, ConnectionString 我有一个表,名为FacilityDatabaseConnection,类似,ID,FacilityID,DatabaseTypeID,ConnectionString

So given a FacilityID and DatabaseTypeID pair you'd get a ConnectionString. 因此,给定FacilityID和DatabaseTypeID对,您将获得一个ConnectionString。 Both Facility and DatabaseType Tables have "Name" Fields. 设施表和数据库类型表都具有“名称”字段。 I would like to make a "Name" field in FacilityDatabaseConnection to do the following, 我想在FacilityDatabaseConnection中创建一个“名称”字段来执行以下操作,

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" 这样它就返回“ 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. 假设这是SQL Server,则计算列不能引用其他表,因此您所建议的是不可能的。

See also http://msdn.microsoft.com/en-us/library/ms191250%28v=sql.105%29.aspx 另请参阅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. 然后,UDF可以访问另一个表。

The alter statement looks something like: alter语句类似于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM