为什么全文目录在后面的代码中不起作用?

时间:2014-02-13 11:17:27

标签: c# sql sql-server-2008 c#-4.0

我的查询如下:

use DBName
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].StackOverflow(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Stackoverflow] [varchar](250) NULL,
    [ResponseBody] [nvarchar](max) NULL

 CONSTRAINT [PK_ResponseBody] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].StackOverflow ON
INSERT [dbo].StackOverflow ([Id], [Stackoverflow], [ResponseBody]) VALUES (1, '[Stackoverflow]','[ResponseBody]')
INSERT [dbo].StackOverflow ([Id], [Stackoverflow], [ResponseBody]) VALUES (2, '[Stackoverflow]','[ResponseBody]')
INSERT [dbo].StackOverflow ([Id], [Stackoverflow], [ResponseBody]) VALUES (3, '[Stackoverflow]','[ResponseBody]')
SET IDENTITY_INSERT [dbo].StackOverflow OFF

CREATE FULLTEXT CATALOG StackOverflowCatalog CREATE FULLTEXT INDEX ON StackOverflow (ResponseBody)
KEY INDEX PK_ResponseBody
ON StackOverflowCatalog

当我将它运行到MS-SQL Management Studio时,它可以工作并给出结果:

  

查询已成功执行

但是当我从代码隐藏中运行它时会出错:

  

CREATE FULLTEXT CATALOG语句不能在用户内部使用   交易。
  CREATE FULLTEXT INDEX语句不能在一个内部使用   用户交易。

代码隐藏在下面:

var regex = new Regex("^GO", RegexOptions.IgnoreCase | RegexOptions.Multiline);
string[] lines = regex.Split(sql);
SqlTransaction transaction = connection.BeginTransaction();
using (SqlCommand cmd = connection.CreateCommand())
{
    cmd.Connection = connection;
    cmd.Transaction = transaction;
    foreach (string line in lines)
    {
        if (line.Length > 0)
        {
            cmd.CommandText = line;
            cmd.CommandType = CommandType.Text;
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch
            {
                transaction.Rollback();
            }
        }
    }
}
transaction.Commit();

1 个答案:

答案 0 :(得分:1)

错误消息告诉您确切原因。在.NET代码中,您将查询包装在SQL事务中。

SqlTransaction transaction = connection.BeginTransaction();
...
{
    ...
    cmd.Transaction = transaction;