使用UDF和视图的

时间:2015-05-15 22:37:35

标签: sql-server-data-tools

遇到一个奇怪的问题。假设在一个空的解决方案中有两个数据库项目,Bart和Homer。 Bart已被添加为荷马的数据库参考。

Bart项目定义了一个函数:

CREATE FUNCTION [dbo].[Message]()
RETURNS NVARCHAR(255)
AS
BEGIN
    RETURN 'I am a value returned from another database'
END

然后荷马项目定义了一个表:

CREATE TABLE [dbo].[Messages]
(
     [Id] INT NOT NULL PRIMARY KEY
)

和观点:

CREATE VIEW [dbo].[MessagesV]
    AS SELECT Id, Bart.dbo.Message() AS [Message]
    FROM dbo.Messages

尝试构建时,我遇到了这些错误:

Error   2   SQL71501: Computed Column: [dbo].[MessagesV].[Message] 
contains an unresolved reference to an object. Either the object does 
not exist or the reference is ambiguous because it could refer to any 
of the following objects: [Bart].[dbo].[Message] or 
[dbo].[Messages].[Bart]::[dbo].[Message].   

Error   1   SQL71501: View: [dbo].[MessagesV] contains an unresolved
reference to an object. Either the object does not exist or the reference 
is ambiguous because it could refer to any of the following objects: 
[Bart].[dbo].[Message] or [dbo].[Messages].[Bart]::[dbo].[Message]. 

如何在视图中正确引用Bart UDF?

1 个答案:

答案 0 :(得分:2)

添加数据库引用时,默认情况下会设置要在TSQL脚本中使用的数据库变量。这允许您的项目以多个环境为目标,其中引用的DB可能具有不同的名称。

此默认设置的正确用法是:

CREATE VIEW [dbo].[MessagesV]
AS SELECT Id, [$(Bart)].dbo.Message() AS [Message]
FROM dbo.Messages

我已经验证了这适用于您发送的代码段。请注意,如果您确实想直接使用数据库名称,则可以在添加引用时删除数据库变量值。然后Bart.dbo.Message()将按预期的那样工作。

下面显示的是“添加数据库引用”对话框,其中显示了相关的数据库变量和示例用法。您将看到使用情况的变化取决于数据库变量文本框中是否有任何文本。

enter image description here

相关问题