我正在尝试执行 sql 文本文件以在 sql server db 上创建存储过程。我还使用此方法创建存储过程将使用的用户定义表类型。
表类型的创建工作完美。但是,当我创建存储过程时出现错误,“CREATE/ALTER PROCEDURE”必须是查询批处理中的第一条语句。
这是读取文件并针对数据库执行它的代码:
public static void LoadStoredProcedures()
{
const string procedureLocation = "C:\\StoredProcedures.txt";
var reader = File.ReadAllText(procedureLocation);
var context = new prismEntities();
context.Database.ExecuteSqlCommand(reader);
}
public static void CreateTables()
{
const string tableLocation = "C:\\CreateTables.txt";
var reader = File.ReadAllText(tableLocation);
var context = new prismEntities();
context.Database.ExecuteSqlCommand(reader);
}
用户定义表的示例:
if not exists (select * from sys.table_types
where name like 'TextbookTable')
create type [dbo].[TextbookTable] as table (
[TXUID] [int] NOT NULL,
[SKU] [int] NOT NULL,
[UsedSKU] [int] NOT NULL,
[BindingID] [int] NOT NULL,
[TextStatusID] [int] NOT NULL,
[StatusDate] [datetime] NULL,
[Author] [char](45) NOT NULL,
[Title] [char](80) NOT NULL,
[ISBN] [char](30) NULL,
[Imprint] [char](10) NULL,
[Edition] [char](2) NULL,
[Copyright] [char](2) NULL,
[Type] [char](10) NULL,
[Bookkey] [varchar](10) NULL,
[Weight] [decimal](10, 4) NULL,
[ImageURL] [char](128) NULL,
primary key clustered
(
[TXUID] ASC
) with (ignore_dup_key = on)
)
我正在尝试创建的存储过程的示例:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AddTextbook]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[AddTextbook]
create procedure [dbo].[AddTextbook]
(
@textbook TextbookTable readonly
)
as
begin
set nocount on;
set identity_insert textbook on
begin try
merge Textbook txt
using (select * from @textbook) as source
on txt.TXUID = source.TXUID
when not matched then
insert (TXUID, SKU, UsedSKU, BindingID, TextStatusID, StatusDate, Author,
Title, ISBN, Imprint, Edition, Copyright, Type, Bookkey, Weight, ImageURL)
values ( source.TXUID, source.SKU, source.UsedSKU, source.BindingID, source.TextStatusID,
source.StatusDate, source.Author, source.Title, source.ISBN,
source.Imprint, source.Edition,
source.Copyright, source.Type, source.Bookkey, source.Weight, source.ImageURL);
set identity_insert textbook off
end try
begin catch
declare @message varchar(128) = error_message()
select
ERROR_NUMBER() as ErrorNumber,
ERROR_SEVERITY() as ErrorSeverity,
ERROR_STATE() as ErrorState,
ERROR_PROCEDURE() as ErrorProcedure,
ERROR_LINE() as ErrorLine,
ERROR_MESSAGE() as ErrorMessage;
raiserror(@message, 16, 10)
end catch
end
grant execute on [dbo].[AddTextbook] to [public]
现在,调用的顺序是首先调用 CreateTables,然后调用 LoadStoredProcedures。表的创建没有问题。未创建存储过程并生成上述错误。我已经删除了“如果存在...”行,存储过程将被创建,但是,如果我试图在同一个文件中创建其他存储过程,它们将出错并且不会被创建。我希望能够用一个文件来管理它,而不是每个存储过程的多个文件。
有谁知道解决这个问题?希望我提供了充足的信息。提前致谢。