SQL:如何在C#中执行此查询 [英] SQL : How Execute this Query in C#

查看:57
本文介绍了SQL:如何在C#中执行此查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





看我有这个查询

hi ,

look i have this query

USE [master]
GO
/****** Object:  Database [DLandS]    Script Date: 07/02/2011 23:40:07 ******/
CREATE DATABASE [DLandS] ON  PRIMARY 
( NAME = N'DLandS', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\DLandS.mdf' , SIZE = 5120KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'DLandS_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\DLandS_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
ALTER DATABASE [DLandS] SET COMPATIBILITY_LEVEL = 100
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [DLandS].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [DLandS] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [DLandS] SET ANSI_NULLS OFF
GO
ALTER DATABASE [DLandS] SET ANSI_PADDING OFF
GO
ALTER DATABASE [DLandS] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [DLandS] SET ARITHABORT OFF
GO
ALTER DATABASE [DLandS] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [DLandS] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [DLandS] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [DLandS] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [DLandS] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [DLandS] SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [DLandS] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [DLandS] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [DLandS] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [DLandS] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [DLandS] SET  DISABLE_BROKER
GO
ALTER DATABASE [DLandS] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [DLandS] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [DLandS] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [DLandS] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [DLandS] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [DLandS] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [DLandS] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [DLandS] SET  READ_WRITE
GO
ALTER DATABASE [DLandS] SET RECOVERY FULL
GO
ALTER DATABASE [DLandS] SET  MULTI_USER
GO
ALTER DATABASE [DLandS] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [DLandS] SET DB_CHAINING OFF
GO
EXEC sys.sp_db_vardecimal_storage_format N'DLandS', N'ON'
GO

USE [DLandS]
GO
/****** Object:  Table [dbo].[attachment_tab]    Script Date: 07/02/2011 23:37:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[attachment_tab](
	[attachment_id] [bigint] NOT NULL,
	[notes] [nvarchar](1000) NULL,
	[attachment_name] [nvarchar](500) NULL,
	[attachment_price] [money] NULL,
 CONSTRAINT [PK_ATTACHMENT] PRIMARY KEY CLUSTERED 
(
	[attachment_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
INSERT [dbo].[attachment_tab] ([attachment_id], [notes], [attachment_name], [attachment_price]) VALUES (0, N'hhgg', N'hfghfg', 60.0000)
INSERT [dbo].[attachment_tab] ([attachment_id], [notes], [attachment_name], [attachment_price]) VALUES (1, NULL, N'enas saeek', 7.0000)
/****** Object:  Table [dbo].[Attachment_Seq]    Script Date: 07/02/2011 23:37:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Attachment_Seq](
	[Seq] [bigint] NOT NULL,
	[Count_Row] [bigint] NOT NULL,
 CONSTRAINT [PK_ATTACHMENT_SEQ] PRIMARY KEY CLUSTERED 
(
	[Seq] 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
INSERT [dbo].[Attachment_Seq] ([Seq], [Count_Row]) VALUES (25, 19)
/****** Object:  StoredProcedure [dbo].[Attachment_Update]    Script Date: 07/02/2011 23:37:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE  [dbo].[Attachment_Update]
@attachment_id BIGINT,
@attachment_name NVARCHAR(500) ,
@attachment_price  MONEY,
@notes nvarchar(1000)
AS
SET NOCOUNT ON begin transaction  
update [dbo].[attachment_tab] set [attachment_id]=@attachment_id,
[attachment_name]=@attachment_name,
[attachment_price]=@attachment_price,[notes]=@notes
where [attachment_id]= @attachment_id 
commit transaction
GO
/****** Object:  StoredProcedure [dbo].[Attachment_Insert]    Script Date: 07/02/2011 23:37:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE  [dbo].[Attachment_Insert]
@attachment_name NVARCHAR(500) = '',
@attachment_price  MONEY = 0,
@notes nvarchar(1000)
AS
SET NOCOUNT ON
DECLARE @attachment_id BIGINT;
SELECT TOP 1  @attachment_id= [Seq] FROM [dbo].[attachment_Seq] 
INSERT INTO [dbo].[attachment_tab]([attachment_id],[attachment_name],[attachment_price],[notes])
VALUES (@attachment_id,@attachment_name,@attachment_price,@notes)
UPDATE [dbo].[attachment_Seq]  
SET Seq=(@attachment_id+1)
, Count_Row =(Count_Row+1) commit transaction
GO
/****** Object:  StoredProcedure [dbo].[Attachment_Delete]    Script Date: 07/02/2011 23:37:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[Attachment_Delete]
@attachment_id bigint = 0 
AS
SET NOCOUNT ON begin transaction
UPDATE [dbo].[attachment_Seq]  
SET Count_Row= (Count_Row-1);
DELETE FROM [dbo].[attachment_tab] 
WHERE [attachment_id]= @attachment_id 
commit transaction
GO









但是当我执行此查询时抛出异常

喜欢这个





but when i Execute this query is throw Exception
Like this

Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near the keyword 'INSERT'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near the keyword 'INSERT'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Must declare the scalar variable "@attachment_id".
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Must declare the scalar variable "@attachment_name".
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.









这是代码:







and this is code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args)
        {
            string connsql = "Data Source=" + Environment.MachineName + ";Integrated Security=True;Pooling=False;MultipleActiveResultSets=False;Packet Size=4096";
            SqlConnection conn = new SqlConnection(connsql);
            conn.Open();
            StreamReader readfilequery = new StreamReader(@"J:\Project\Finelf\Dental lab and Storeff\Main Form\query\script.sql");
            string query = readfilequery.ReadToEnd();
            SqlCommand commqnd = new SqlCommand(query, conn);
            commqnd.ExecuteNonQuery();//(here throw Exception)
        }
    }
}







帮助我..............




help me ..............

推荐答案

您必须逐个拆分查询并执行命令。这并不难。基本上,您累积行直到找到带有GO的行,然后执行该查询。然后跳过该行(使用GO)并开始累积下一个查询。然后重复,直到你到达文件末尾。
You will have to split the query and execute command one by one. It is not that hard. Essentially, you accumulate lines until you find a line with "GO" and then you execute that query. You then skip that line (with "GO") and start accumulating next query. You then repeat until you reach then end of the file.


非常感谢

看我写这个代码它成功了

这是解决方案



thank you very much
look i wrote this code it is succeeded
this is solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args)
        {
            string connsql = "Data Source=" + Environment.MachineName + ";Integrated Security=True;Pooling=False;MultipleActiveResultSets=False;Packet Size=4096";
            SqlConnection conn = new SqlConnection(connsql);
            conn.Open();
            StreamReader readfilequery = new StreamReader(@"J:\Project\Finelf\Dental lab and Storeff\Main Form\query\script.sql");
            string query = "";
            string line = readfilequery.ReadLine();
            while (line != null)
            {
                if (line.IndexOf("GO") == -1)
                {
                    query =query +" "+ line;
                }
                else
                {
                    SqlCommand commqnd = new SqlCommand(query, conn);
                    commqnd.ExecuteNonQuery();
                    query = null;
                }
                line = readfilequery.ReadLine();
            }
            
        }
    }
}


Noze的代码不会运行最后一个块命令..

小修复:



Noze's code would not run the last block of commands..
small fix:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args)
        {
            string connsql = "Data Source=" + Environment.MachineName + ";Integrated Security=True;Pooling=False;MultipleActiveResultSets=False;Packet Size=4096";
            SqlConnection conn = new SqlConnection(connsql);
            conn.Open();
            StreamReader readfilequery = new StreamReader(@"J:\Project\Finelf\Dental lab and Storeff\Main Form\query\script.sql");
            string query = "";
            string line = readfilequery.ReadLine();
            while (line != null)
            {
                if (line != "GO")
                {
                    query =query +" "+ line;
                }
                else
                {
                    (new SqlCommand(query, conn)).ExecuteNonQuery();
                    query = null;
                }
                line = readfilequery.ReadLine();
            }
            if (!string.IsNullOrEmpty(query)) //last time
            {
                (new SqlCommand(query, conn)).ExecuteNonQuery();
                query = null;
            }
        }
    }
}


这篇关于SQL:如何在C#中执行此查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆