【问题标题】:Have a CREATE TABLE or CREATE PROCEDURE automatically determine column type in SSMS?是否有 CREATE TABLE 或 CREATE PROCEDURE 自动确定 SSMS 中的列类型?
【发布时间】:2020-05-29 15:00:37
【问题描述】:

我有一个用于设置表、存储过程、视图等的数据库创建脚本。当我在创建表语句中更改列的类型时,我希望此更改反映在创建存储过程/视图/ etc 引用该表的语句,而无需遍历并手动更改每个语句。

换句话说,我希望我的存储过程在创建时根据另一列的类型自动确定列类型。在我迭代设计和原型制作时,我不需要它来处理包含数据的实时数据库。

在这个(虚构的)示例中类似于TYPE_OF()

create table Logs
(
    id              int identity(1, 1) primary key,
    userName        varchar(32),
    logType         int foreign key references LogType(id),
    description     varchar(128),
    datestamp       datetime
);
go

create procedure WriteLog
(
    @userName       TYPE_OF(Logs.userName),   -- should be varchar(32),
    @logType        int,
    @description    TYPE_OF(Logs.description)    -- should be varchar(128)
)
as
begin

    insert into Logs
    values(@userName, @logType, @description, SYSDATETIME());

end
go;

我想我记得来自 Oracle / SQL Plus / PLSQL 的类似内容,但我找不到它。

我正在使用 SQL Server Management Studio v18.4

【问题讨论】:

  • 不,没有这样的事情。您必须手动更新所有依赖项。
  • 您可以探索在sp_depends 的结果上运行sp_recompile。我怀疑有很多问题可以找到。

标签: sql-server tsql ssms


【解决方案1】:

不确定您正在寻找的 TYPEOF 功能是否存在,但您可以尝试使用 DDL Trigger 以使您的过程与列类型更改保持同步。

每次更改表时都会触发此触发器,您只需解析 EVENTDATA() 即可查看 Logs 表中的列类型是否已更改。触发器的主体看起来像这样:

CREATE TRIGGER OnLogsChanged
ON DATABASE
FOR ALTER_TABLE
AS
BEGIN
    -- 1. Parse EVENTDATA() to see if the Logs table was altered

    -- 2. If it has, store the definition of the WriteLog procedure into a variable by reading it from sys.procedures

    -- 3. Read the new types for the columns of the Logs table from sys.all_columns

    -- 4. replace the parameter declarations in the procedure definition to match the new types in the Logs table

    -- 5. alter the procedure with the new definition by building up the ALTER PROCEDURE statement as a string and executing it with sp_executesql
END

只要触发器保持启用,您的过程就应该与表列类型保持同步。

【讨论】:

  • 这确实可以满足我的要求,但每次我想更改新的 dbo 时都会增加编写触发器和更改语句的复杂性。它确实有可能保留数据,但我也可以只编辑 create 语句; use SSMS to generate insert statements from the table's data;并重新生成整个数据库,如果测试数据不是很大,在大多数情况下这可能会更快。我认为你是对的,我不想要的东西不存在。
猜你喜欢
  • 2021-12-22
  • 1970-01-01
  • 2019-03-30
  • 2013-12-27
  • 2013-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多