2016-04-13 38 views
0

我正在尝试创建一个将列值更改为大写的CLR触发器。 但是当我尝试建立我获取文件如下:CLR触发无法解析的参考错误

Severity Code Description Project File Line Suppression State 
Error  SQL71501: Trigger: [dbo].[UpperTrigger] has an unresolved reference to object [dbo].[tblAirline]. TravelSight \\mac\home\documents\visual studio 2015\Projects\TravelSight\TravelSight\obj\Debug\TRAVELSIGHT.generated.sql 33 

我的CLR代码如下:

using System; 
using System.Data; 
using System.Data.SqlClient; 
using Microsoft.SqlServer.Server; 

public partial class Triggers 
{ 
    // Enter existing table or view for the target and uncomment the attribute line 
    [Microsoft.SqlServer.Server.SqlTrigger(Name = "UpperTrigger", Target = "[dbo].[tblAirline]", Event = "AFTER INSERT, UPDATE")] 
    public static void UpperTrigger() 
    { 
     // Open connection for context 
     SqlConnection conn = new SqlConnection(); 
     conn.ConnectionString = "Context Connection=true"; 

     // Create command object 
     SqlCommand command = new SqlCommand(); 
     command.Connection = conn; 

     // Create string that defines sql statement 
     string sql = 
     "Update tblAirline " + 
     "SET AirlineName = UPPER(AirlineName) " + 
     "WHERE AirlineID IN(SELECT AirlineID FROM Inserted)"; 
     command.CommandText = sql; 

     // Exec command object 
     command.ExecuteNonQuery(); 

     // Close connection object 
     conn.Close(); 

    } 
} 

有什么我错过了吗?

+1

1.为什么使用与tsql触发器相反的CLR触发器? 2.为什么它的上层(sql server不区分大小写)很重要? – Wjdavis5

+0

你是否有这个名字为tblAirline的表,如果是,请尝试使用此tblAirline而不是[dbo]。[tblAirline] – rashfmnb

+2

SQL可以区分大小写 - 这取决于您的归类。点击这里:https://msdn.microsoft.com/en-us/library/ms144250(v=sql.105).aspx – Andez

回答

1

错误消息来自Visual Studio/SSDT。

错误的最可能原因是在项目中定义了SqlTrigger属性的Target属性中引用的表。您需要将“添加新项目”添加到项目中,然后选择“表格”。添加表tblAirline与数据库中存在的完全相同,因为在部署时,任何差异都会传播到数据库。

其他说明:

  • 请把new SqlConnection实例化一个using(){ }结构的内部,因为它是一次性的对象。
  • 请将new SqlCommand实例化为using(){ }构造,因为它是一个可丢弃的对象。
  • 最好是停止在tbl前缀表名称。这种不好的做法没有好处。你也不应该使用vvw或任何其他名称来加前缀视图名称。
  • 请不要使用SQLCLR除了调用T-SQL。我当然希望这是一个课堂练习/作业,并且从不打算实际上在某天生产,因为它比在此触发器中执行的简单T-SQL查询更难以维护。
+0

this只是一个学习clr触发器的训练练习 – user2371684