2

将列添加到视图所依赖的表时,我对带有命名字段的视图产生了非常意想不到的影响。

SQL:

SELECT     dbo.AccessCustomFieldDepartment.AccessCustomFieldDepartmentID, dbo.AccessCustomFieldDepartment.AccessCustomField_StoreID, 
                      dbo.AccessCustomFieldDepartment.AccessCustomField_ShopOwner, dbo.AccessCustomFieldDepartment.AccessCustomField_CVRnumber, 
                      dbo.AccessCustomFieldDepartment.AccessCustomField_OpenMonToWed, dbo.AccessCustomFieldDepartment.AccessCustomField_OpenMonToThu, 
                      dbo.AccessCustomFieldDepartment.AccessCustomField_OpenMonToFri, dbo.AccessCustomFieldDepartment.AccessCustomField_OpenMonToTue,
--..
--a bunch of other fields
--..

                  dbo.AccessUser.AccessUserAddress, dbo.AccessUser.AccessUserAddress2, dbo.AccessUser.AccessUserZip, dbo.AccessUser.AccessUserCity, 
                  dbo.AccessUser.AccessUserCountry, dbo.AccessUser.AccessUserWeb
FROM         dbo.AccessUser INNER JOIN
                      dbo.AccessCustomFieldDepartment ON dbo.AccessUser.AccessUserID = dbo.AccessCustomFieldDepartment.AccessCustomFieldDepartmentID

当其他人的代码对表AccessUser进行动态添加列时,服务器或其他东西会更改视图的sql!

例如:

dbo.AccessUser.AccessUserCountry, dbo.AccessUser.AccessUserWeb

更改为

dbo.AccessUser.AccessUserCountry AS AccessUserCity, 
dbo.AccessUser.AccessUserWeb AS AccessUserCountry

这极大地影响了我对数据的最终呈现......就像视图试图保持各个列的位置一样。

删除该列会神奇地将 sql 更改回原始状态。

所以问题是:

  • 到底是怎么回事?是服务器吗?CMS 软件中的一些功能(添加字段功能所在的位置)
  • 我可以在视图上进行设置以使其 sql 语句 100% 静态吗?

问候,

斯蒂恩

4

1 回答 1

1

要重新编译视图或过程,请执行以下操作:

/* View: */
exec sp_refreshview 'dbo.MyViewName'

/* Procedure, FN, IF, TF */
exec sp_recompile 'dbo.ProcedureName'
exec sp_recompile 'dbo.ScalarFunctionName'
exec sp_recompile 'dbo.InlineFunctionName'
exec sp_recompile 'dbo.TableFunctionName'

您可以从 sysobjects 获取对象列表。将这些选择到表变量中应该相对容易,并生成一个循环,依次重新编译每个变量。

set nocount on
declare @o table(
    id int primary key,
    object_full_name nvarchar(1000),
    xtype nvarchar(20)
)
insert @o
select
    id, object_schema_name(id) + '.' + object_name(id) as object_full_name, xtype
from sysobjects so 
where 
    xtype in ('V', 'P', 'FN', 'TF', 'IF')


while exists (select 1 from @o)
begin
    declare @id int
    declare @object_full_name nvarchar(1000)
    declare @xtype nvarchar(20)
    set @id = null
    select top 1 @id = id, @object_full_name = object_full_name, @xtype = xtype from @o order by xtype, object_full_name, id
    delete @o where id = @id
    if @xtype = 'V'
    begin
        raiserror('Marking for recompile - %s: %s', 0, 1, @xtype, @object_full_name)
        exec dbo.sp_refreshview @object_full_name
    end
    else
    begin
        raiserror('Marking for recompile - %s: %s', 0, 1, @xtype, @object_full_name)
        exec dbo.sp_recompile @object_full_name
    end
end

您还可以考虑使用 DDL 触发器来按需执行此操作。

于 2012-04-27T11:36:18.080 回答