एक बड़ी SQL स्क्रिप्ट निष्पादित करें (GO कमांड के साथ)


89

मुझे C # प्रोग्राम के भीतर से SQL कथन (तालिकाओं, विचारों और संग्रहीत कार्यविधियों का एक गुच्छा बनाते हुए) के एक बड़े सेट को निष्पादित करने की आवश्यकता है।

इन बयानों को बयानों से अलग करने की जरूरत है GO, लेकिन बयानों को SqlCommand.ExecuteNonQuery()पसंद नहीं GOकरते। मेरा समाधान, जो मुझे लगता है कि मैं संदर्भ के लिए पोस्ट करूंगा, GOलाइनों पर एसक्यूएल स्ट्रिंग को विभाजित करना था , और प्रत्येक बैच को अलग से निष्पादित करना था।

क्या कोई आसान / बेहतर तरीका है?

जवाबों:


105

SQL सर्वर प्रबंधन ऑब्जेक्ट (SMO) का उपयोग करें जो GO विभाजकों को समझता है। मेरी ब्लॉग पोस्ट यहाँ देखें: http://weblogs.asp.net/jongalloway/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts- 2D00 -the-easy-way

नमूना कोड:

public static void Main()    
{        
  string scriptDirectory = "c:\\temp\\sqltest\\";
  string sqlConnectionString = "Integrated Security=SSPI;" +
  "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)";
  DirectoryInfo di = new DirectoryInfo(scriptDirectory);
  FileInfo[] rgFiles = di.GetFiles("*.sql");
  foreach (FileInfo fi in rgFiles)
  {
        FileInfo fileInfo = new FileInfo(fi.FullName);
        string script = fileInfo.OpenText().ReadToEnd();
        using (SqlConnection connection = new SqlConnection(sqlConnectionString))
        {
            Server server = new Server(new ServerConnection(connection));
            server.ConnectionContext.ExecuteNonQuery(script);
        }
   }
}

यदि वह आपके लिए काम नहीं करेगा, तो फिल हॅक की लाइब्रेरी देखें जो कि संभालती है: http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators -and.aspx


2
इसे लेनदेन के साथ कैसे जोड़ा जा सकता है? SqlConnection के साथ ServerConnection बनाते समय कोड एक InvalidOperationException फेंकता है, जिस पर एक लंबित लेनदेन होता है।
बेनपैरस

1
यह समाधान काम करता है, मैं सिर्फ यह जोड़ना चाहता हूं कि यदि आप किसी ऐसी वस्तु के साथ लेन-देन का उपयोग करना चाहते हैं, तो TransactionScopeआपको केवल वर्तमान महत्वाकांक्षी लेनदेन के साथ कनेक्शन को सूचीबद्ध करना होगा। मेरा जवाब यहां देखें: stackoverflow.com/a/18322938/1268570
Jupaol

महान काम करता है, लेकिन हम SqlConnection.InfoMessageसी # एप्लिकेशन में परिणाम देखने के लिए याtxt फ़ाइल में परिणाम को बचाने के लिए ) का उपयोग कर सकते हैं , बस यह जानने के लिए कि क्या स्क्रिप्ट सफलतापूर्वक निष्पादित की गई थी, क्योंकि हाल ही में sqlcmdजब मैंने दूरस्थ होस्ट पर 150 एमबी स्क्रिप्ट फ़ाइल निष्पादित की, तो 55 मिनट के बाद कुछ पंक्तियों इस त्रुटि के साथ प्रभावित कर रहे थे, , ।TCP Provider: An existing connection was forcibly closed by the remote host. communication link failureप्रभावित पंक्तियों में से कोई भी ज्ञात नहीं हो सकता है, लेकिन मैं डेटाबेस उत्पन्न स्क्रिप्ट फ़ाइल को चलाते समय त्रुटि संदेशों के बारे में चिंतित हूं।
शैजुत

5
जब SQL Dlls मशीन पर स्थापित नहीं होते हैं तो यह समाधान आपके कोड को विफल कर देता है। .NET विंडोज में निर्मित कुछ dll का उपयोग करता है। कुछ SQL सुविधा पैक (प्रबंध ऑब्जेक्ट सहित) की अनुपस्थिति 'Microsoft.SqlServer.SqlClrProvider.dll' जैसी कुछ त्रुटियों को नहीं रोक सकती है। इसे ठीक करना (यह आसान काम नहीं है) अगली त्रुटि होगी 'Microsoft.SqlServer.BathParser.dll' आदि अपने आवेदन के लिए लचीलापन सुनिश्चित करने के लिए अन्य समाधान खोजें।
एलेक्जेंड्रा सरगस्यान

35

अपनी तात्कालिक समस्या को हल करने के लिए मैंने एक साथ दस्तक दी।

private void ExecuteBatchNonQuery(string sql, SqlConnection conn) {
    string sqlBatch = string.Empty;
    SqlCommand cmd = new SqlCommand(string.Empty, conn);
    conn.Open();
    sql += "\nGO";   // make sure last batch is executed.
    try {
        foreach (string line in sql.Split(new string[2] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries)) {
            if (line.ToUpperInvariant().Trim() == "GO") {
                cmd.CommandText = sqlBatch;
                cmd.ExecuteNonQuery();
                sqlBatch = string.Empty;
            } else {
                sqlBatch += line + "\n";
            }
        }            
    } finally {
        conn.Close();
    }
}

इसके लिए GO कमांड की आवश्यकता है कि वे अपनी लाइन पर हों, और ब्लॉक-कमेंट्स का पता नहीं लगाएंगे, इसलिए इस तरह की चीज़ विभाजित हो जाएगी, और एक त्रुटि:

ExecuteBatchNonQuery(@"
    /*
    GO
    */", conn);

यह अच्छा है कि जरूरत पड़ने पर मैं इसे आसानी से SqlCe में बदल सकता हूं - दूसरा कोड Sql कनेक्शन क्लासेस और कमांड का उपयोग करता है।
ब्लू टॉक

मैं इस कोड को SQL स्क्रिप्ट के साथ कई संग्रहित प्रक्रियाओं के साथ चलाना चाहता हूं, लेकिन मैं थोड़ा भ्रमित हूं, यह SQL कहां पढ़ता है? जब आप 'अंतिम बैच' का संदर्भ देते हैं तो क्या आपका मतलब SQL कोड है? और यदि हां, तो आप अंतिम बैच का निर्धारण कैसे करेंगे, और क्या होगा यदि मैं सभी बैचों को केवल अंतिम नहीं चलाना चाहता हूं? बहुत सारे सवाल जो मुझे पता हैं, लेकिन अगर आपके पास जवाब देने का समय है तो धन्यवाद।
user1676874

आप SQL को फ़ंक्शन के लिए एक स्ट्रिंग के रूप में पास करते हैं: string sql- यह पूरी स्क्रिप्ट है। जब मैं "बैच" का संदर्भ लेता हूं, तो मेरा मतलब दो "गो" स्टेटमेंट्स के बीच SQL कोड का एक हिस्सा है। यदि आप स्क्रिप्ट के साथ अपनी स्क्रिप्ट को समाप्त नहीं करते हैं GOतो कोड स्क्रिप्ट के अंत में एक कोड जोड़ता है ताकि foreachअंतिम बैच को छोड़ न सके GO। तो जैसा कि लिखा गया कोड सभी SQL को निष्पादित करेगा।
Blorgbeard

मैंने एक एक्सटेंशन विधि बनाई: आंतरिक स्थिर वर्ग SqlCommandHelper {आंतरिक स्थैतिक शून्य ExecuteBatchNonQuery (यह SqlCommand cmd, string sql)
रोब

1
यदि आप एक अधिक कुशल होना चाहते हैं तो आप StringBuilder sqlBatchइसके बजाय उपयोग कर सकते हैं ।
Lii

11

इसे निष्पादित करने के लिए आप SQL प्रबंधन ऑब्जेक्ट का उपयोग कर सकते हैं । ये वही ऑब्जेक्ट हैं जो मैनेजमेंट स्टूडियो प्रश्नों को निष्पादित करने के लिए उपयोग करता है। मुझे विश्वास है Server.ConnectionContext.ExecuteNonQuery()कि आपको जो चाहिए वह प्रदर्शन करेगा।


6

"GO" बैच विभाजक कीवर्ड वास्तव में SQL प्रबंधन स्टूडियो द्वारा ही उपयोग किया जाता है, ताकि यह पता चले कि सर्वर को भेजने वाले बैचों को कहां समाप्त करना है, और यह SQL सर्वर को पारित नहीं किया गया है। आप भी प्रबंधन स्टूडियो में कीवर्ड बदल सकते हैं, तो क्या आपकी इच्छा होनी चाहिए।


5

मैं इस अंत के साथ निर्णय लिया पर कई बार देखो एफई कार्यान्वयन एक के लिए संशोधित बिटSqlConnection

public static void ExecuteSqlScript(this SqlConnection sqlConnection, string sqlBatch)
        {
            // Handle backslash utility statement (see http://technet.microsoft.com/en-us/library/dd207007.aspx)
            sqlBatch = Regex.Replace(sqlBatch, @"\\(\r\n|\r|\n)", string.Empty);

            // Handle batch splitting utility statement (see http://technet.microsoft.com/en-us/library/ms188037.aspx)
            var batches = Regex.Split(
                sqlBatch,
                string.Format(CultureInfo.InvariantCulture, @"^\s*({0}[ \t]+[0-9]+|{0})(?:\s+|$)", BatchTerminator),
                RegexOptions.IgnoreCase | RegexOptions.Multiline);

            for (int i = 0; i < batches.Length; ++i)
            {
                // Skip batches that merely contain the batch terminator
                if (batches[i].StartsWith(BatchTerminator, StringComparison.OrdinalIgnoreCase) ||
                    (i == batches.Length - 1 && string.IsNullOrWhiteSpace(batches[i])))
                {
                    continue;
                }

                // Include batch terminator if the next element is a batch terminator
                if (batches.Length > i + 1 &&
                    batches[i + 1].StartsWith(BatchTerminator, StringComparison.OrdinalIgnoreCase))
                {
                    int repeatCount = 1;

                    // Handle count parameter on the batch splitting utility statement
                    if (!string.Equals(batches[i + 1], BatchTerminator, StringComparison.OrdinalIgnoreCase))
                    {
                        repeatCount = int.Parse(Regex.Match(batches[i + 1], @"([0-9]+)").Value, CultureInfo.InvariantCulture);
                    }

                    for (int j = 0; j < repeatCount; ++j)
                    {
                       var command = sqlConnection.CreateCommand();
                       command.CommandText = batches[i];
                       command.ExecuteNonQuery();
                    }
                }
                else
                {
                    var command = sqlConnection.CreateCommand();
                    command.CommandText = batches[i];
                    command.ExecuteNonQuery();
                }
            }
        }

धन्यवाद @ फीलिप कोर्डस हालांकि यह एक जवाब के रूप में चिह्नित नहीं है, इससे मुझे एक आकर्षण की तरह मदद मिली! हमारे पास बड़ी मात्रा में स्क्रिप्ट थे जहां बैचटर्मिनेटर का उल्लेख विभिन्न तरीकों से किया गया था जैसे ऊपरी और निचले मामलों (गो, गो, गो आदि) के संयोजन और अधिकतम समय में इसके साथ अनुगामी या अग्रणी स्थान थे जो c # के माध्यम से निष्पादन के लिए एक बड़ी समस्या का कारण बने ... । धन्यवाद !!
डिपाक्रिसवादकर 11

2
@DipakRiswadkar हाँ इस सवाल पर कुछ समय के लिए बंद कर दिया गया और कोई भी उत्तर प्रदान नहीं किया गया जो मेरी जरूरतों को पूरा करता है, इसलिए EF कार्यान्वयन को देखा तो अच्छा लगा इसलिए मैंने उत्तर पोस्ट किया।
फिलिप कॉर्डस

बहुत बढ़िया जवाब, यह एक आकर्षण की तरह काम करता है, बहुत बहुत धन्यवाद
जुआन

@ रेले को इसकी रिपोर्ट एंटिटी फ्रेमवर्क टीम को भी देनी चाहिए। जैसा कि मैंने कहा कि यह थोड़े संशोधनों के साथ एक कॉपी अतीत था।
फिलिप कॉर्डस


4

Blorgbeard के समाधान पर आधारित है।

foreach (var sqlBatch in commandText.Split(new[] { "GO" }, StringSplitOptions.RemoveEmptyEntries))
{
   sqlCommand.CommandText = sqlBatch;
   sqlCommand.ExecuteNonQuery();
}

3
नया [] {"गो", "गो", "गो"}
एंड्रयू वेरिगा

1
नया [] {"जीओ", "गो", "गो", "जीओ"}
ब्रैंडन वार्ड

जब तक आपके कोड में दो अक्षरों के लिए कोई अन्य उपयोग नहीं होता है, जैसे कि GOTO-Statements या टिप्पणियां।
पैट्रिक

3

यदि आप SMO का उपयोग नहीं करना चाहते हैं, उदाहरण के लिए क्योंकि आपको क्रॉस-प्लेटफ़ॉर्म होने की आवश्यकता है, तो आप SubText से ScriptSplitter क्लास का भी उपयोग कर सकते हैं।

यहाँ C # & VB.NET में कार्यान्वयन है

उपयोग:

    string strSQL = @"
SELECT * FROM INFORMATION_SCHEMA.columns
GO
SELECT * FROM INFORMATION_SCHEMA.views
";

    foreach(string Script in new Subtext.Scripting.ScriptSplitter(strSQL ))
    {
        Console.WriteLine(Script);
    }

यदि आपको मल्टीलाइन सी-स्टाइल टिप्पणियों के साथ समस्या है, तो regex के साथ टिप्पणियों को हटा दें:

static string RemoveCstyleComments(string strInput)
{
    string strPattern = @"/[*][\w\d\s]+[*]/";
    //strPattern = @"/\*.*?\*/"; // Doesn't work
    //strPattern = "/\\*.*?\\*/"; // Doesn't work
    //strPattern = @"/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/ "; // Doesn't work
    //strPattern = @"/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/ "; // Doesn't work

    // http://stackoverflow.com/questions/462843/improving-fixing-a-regex-for-c-style-block-comments
    strPattern = @"/\*(?>(?:(?>[^*]+)|\*(?!/))*)\*/";  // Works !

    string strOutput = System.Text.RegularExpressions.Regex.Replace(strInput, strPattern, string.Empty, System.Text.RegularExpressions.RegexOptions.Multiline);
    Console.WriteLine(strOutput);
    return strOutput;
} // End Function RemoveCstyleComments

एकल-पंक्ति टिप्पणियों को हटाना यहां है:

https://stackoverflow.com/questions/9842991/regex-to-remove-single-line-sql-comments

क्या यह वर्ग /* Go */मामले पर विचार करता है ?
edgarmtze

@cMinor: फाड़नेवाला में नहीं है, लेकिन आप विभाजन से पहले रेगेक्स के साथ बहु-टिप्पणियों को हटा सकते हैं।
स्टीफन स्टीगर

2

मुझे भी एक ही समस्या का सामना करना पड़ा, और मुझे कोई और रास्ता नहीं मिला, लेकिन अलग-अलग फाइलों में एकल SQL ऑपरेशन को विभाजित करना, फिर उन सभी को अनुक्रम में निष्पादित करना।

स्पष्ट रूप से समस्या डीएमएल आदेशों की सूची के साथ नहीं है, उन्हें बीच में बिना जीओ के निष्पादित किया जा सकता है; DDL के साथ अलग कहानी (बनाएं, बदलें, ड्रॉप करें ...)


2

यदि आप SMO मार्ग पर नहीं जाना चाहते हैं, तो आप "GO" के लिए खोज और प्रतिस्थापित कर सकते हैं ;; और क्वेरी के रूप में आप करेंगे। ध्यान दें कि अंतिम परिणाम सेट को हल कर दिया जाएगा।


1
वे ExecuteNonQuery निष्पादित कर रहे हैं। यह अब तक का सबसे आसान तरीका है।
डेवमार्गनटैक्सस

3
"गो" का उपयोग करने से आप बैच में अगले कमांड में फिर से उसी चर को परिभाषित कर पाएंगे। अर्धविराम लगाने से ऐसा नहीं होगा।
DDRider62

2

मैंने अपनी एसक्यूएल को एक टेक्स्ट फाइल से एक स्ट्रिंग में लोड करके आज इसे पूरा किया। मैंने स्ट्रिंग को अलग-अलग कमांड में अलग करने के लिए स्ट्रिंग स्प्लिट फ़ंक्शन का उपयोग किया, जो तब सर्वर को व्यक्तिगत रूप से भेजे गए थे। सिम :)

बस एहसास हुआ कि आपको केवल \ nGO पर विभाजन करने की आवश्यकता है यदि पत्र आपके किसी भी टेबल के नाम आदि में दिखाई देते हैं, तो अनुमान करें कि मैं वहां भाग्यशाली था!


2

यदि आप एसएमओ का उपयोग नहीं करना चाहते हैं (जो नीचे दिए गए समाधान से बेहतर है, लेकिन मैं एक विकल्प देना चाहता हूं ...) आप इस फ़ंक्शन के साथ अपनी क्वेरी को विभाजित कर सकते हैं।

यह है:

  • टिप्पणी प्रमाण (उदाहरण - GO या / * GO * /)
  • केवल एक नई लाइन पर काम करता है, जैसे कि SSMS में (उदाहरण / * परीक्षण / * GO काम करता है और 1 का चयन करें जैसे कि नहीं जाना
  • स्ट्रिंग प्रूफ (उदाहरण प्रिंट 'नो गो')

    private List<string> SplitScriptGo(string script)
    {
        var result = new List<string>();
        int pos1 = 0;
        int pos2 = 0;
        bool whiteSpace = true;
        bool emptyLine = true;
        bool inStr = false;
        bool inComment1 = false;
        bool inComment2 = false;
    
        while (true)
        {
            while (pos2 < script.Length && Char.IsWhiteSpace(script[pos2]))
            {
                if (script[pos2] == '\r' || script[pos2] == '\n')
                {
                    emptyLine = true;
                    inComment1 = false;
                }
    
                pos2++;
            }
    
            if (pos2 == script.Length)
                break;
    
            bool min2 = (pos2 + 1) < script.Length;
            bool min3 = (pos2 + 2) < script.Length;
    
            if (!inStr && !inComment2 && min2 && script.Substring(pos2, 2) == "--")
                inComment1 = true;
    
            if (!inStr && !inComment1 && min2 && script.Substring(pos2, 2) == "/*")
                inComment2 = true;
    
            if (!inComment1 && !inComment2 && script[pos2] == '\'')
                inStr = !inStr;
    
            if (!inStr && !inComment1 && !inComment2 && emptyLine
                && (min2 && script.Substring(pos2, 2).ToLower() == "go")
                && (!min3 || char.IsWhiteSpace(script[pos2 + 2]) || script.Substring(pos2 + 2, 2) == "--" || script.Substring(pos2 + 2, 2) == "/*"))
            {
                if (!whiteSpace)
                    result.Add(script.Substring(pos1, pos2 - pos1));
    
                whiteSpace = true;
                emptyLine = false;
                pos2 += 2;
                pos1 = pos2;
            }
            else
            {
                pos2++;
                whiteSpace = false;
    
                if (!inComment2)
                    emptyLine = false;
            }
    
            if (!inStr && inComment2 && pos2 > 1 && script.Substring(pos2 - 2, 2) == "*/")
                inComment2 = false;
        }
    
        if (!whiteSpace)
            result.Add(script.Substring(pos1));
    
        return result;
    }

1

स्ट्रिंग को विभाजित करने और बैच द्वारा बैच निष्पादित करने के लिए निम्न विधि का उपयोग करें

using System;
using System.IO;
using System.Text.RegularExpressions;
namespace RegExTrial
{
    class Program
    {
        static void Main(string[] args)
        {
            string sql = String.Empty;
            string path=@"D:\temp\sample.sql";
            using (StreamReader reader = new StreamReader(path)) {
                sql = reader.ReadToEnd();
            }            
            //Select any GO (ignore case) that starts with at least 
            //one white space such as tab, space,new line, verticle tab etc
            string pattern="[\\s](?i)GO(?-i)";

            Regex matcher = new Regex(pattern, RegexOptions.Compiled);
            int start = 0;
            int end = 0;
            Match batch=matcher.Match(sql);
            while (batch.Success) {
                end = batch.Index;
                string batchQuery = sql.Substring(start, end - start).Trim();
                //execute the batch
                ExecuteBatch(batchQuery);
                start = end + batch.Length;
                batch = matcher.Match(sql,start);
            }

        }

        private static void ExecuteBatch(string command)
        { 
            //execute your query here
        }

    }
}

1

तृतीय पक्षों से बचने के लिए, रेगेक्स, मेमोरी ओवरहेड्स और बड़ी स्क्रिप्ट के साथ तेजी से काम करने के लिए मैंने अपना स्ट्रीम-आधारित पार्सर बनाया। यह

  • पहले वाक्यविन्यास की जाँच करता है
  • टिप्पणियों को पहचान सकते हैं - या / ** / के साथ

    -- some commented text
     /*
    drop table Users;
    GO
       */
  • "या" के साथ स्ट्रिंग शाब्दिक पहचान कर सकते हैं

    set @s =
        'create table foo(...);
        GO
        create index ...';
  • LF और CR स्वरूपण को संरक्षित करता है
  • ऑब्जेक्ट बॉडीज (संग्रहीत कार्यविधियाँ, विचार आदि) में टिप्पणी ब्लॉक को संरक्षित करता है
  • और अन्य निर्माण जैसे

          gO -- commented text

कैसे इस्तेमाल करे

    try
    {
        using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=DATABASE-NAME;Data Source=SERVER-NAME"))
        {
            connection.Open();

            int rowsAffected = SqlStatementReader.ExecuteSqlFile(
                "C:\\target-sql-script.sql",
                connection,
                // Don't forget to use the correct file encoding!!!
                Encoding.Default,
                // Indefinitely (sec)
                0
            );
        }
    }
    // implement your handlers
    catch (SqlStatementReader.SqlBadSyntaxException) { }
    catch (SqlException) { }
    catch (Exception) { }

स्ट्रीम-आधारित SQL स्क्रिप्ट रीडर

class SqlStatementReader
{
    public class SqlBadSyntaxException : Exception
    {
        public SqlBadSyntaxException(string description) : base(description) { }
        public SqlBadSyntaxException(string description, int line) : base(OnBase(description, line, null)) { }
        public SqlBadSyntaxException(string description, int line, string filePath) : base(OnBase(description, line, filePath)) { }
        private static string OnBase(string description, int line, string filePath)
        {
            if (filePath == null)
                return string.Format("Line: {0}. {1}", line, description);
            else
                return string.Format("File: {0}\r\nLine: {1}. {2}", filePath, line, description);
        }
    }

    enum SqlScriptChunkTypes
    {
        InstructionOrUnquotedIdentifier = 0,
        BracketIdentifier = 1,
        QuotIdentifierOrLiteral = 2,
        DblQuotIdentifierOrLiteral = 3,
        CommentLine = 4,
        CommentMultiline = 5,
    }

    StreamReader _sr = null;
    string _filePath = null;
    int _lineStart = 1;
    int _lineEnd = 1;
    bool _isNextChar = false;
    char _nextChar = '\0';

    public SqlStatementReader(StreamReader sr)
    {
        if (sr == null)
            throw new ArgumentNullException("StreamReader can't be null.");

        if (sr.BaseStream is FileStream)
            _filePath = ((FileStream)sr.BaseStream).Name;

        _sr = sr;
    }

    public SqlStatementReader(StreamReader sr, string filePath)
    {
        if (sr == null)
            throw new ArgumentNullException("StreamReader can't be null.");

        _sr = sr;
        _filePath = filePath;
    }

    public int LineStart { get { return _lineStart; } }
    public int LineEnd { get { return _lineEnd == 1 ? _lineEnd : _lineEnd - 1; } }

    public void LightSyntaxCheck()
    {
        while (ReadStatementInternal(true) != null) ;
    }

    public string ReadStatement()
    {
        for (string s = ReadStatementInternal(false); s != null; s = ReadStatementInternal(false))
        {
            // skip empty
            for (int i = 0; i < s.Length; i++)
            {
                switch (s[i])
                {
                    case ' ': continue;
                    case '\t': continue;
                    case '\r': continue;
                    case '\n': continue;
                    default:
                        return s;
                }
            }
        }
        return null;
    }

    string ReadStatementInternal(bool syntaxCheck)
    {
        if (_isNextChar == false && _sr.EndOfStream)
            return null;

        StringBuilder allLines = new StringBuilder();
        StringBuilder line = new StringBuilder();
        SqlScriptChunkTypes nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
        SqlScriptChunkTypes currentChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
        char ch = '\0';
        int lineCounter = 0;
        int nextLine = 0;
        int currentLine = 0;
        bool nextCharHandled = false;
        bool foundGO;
        int go = 1;

        while (ReadChar(out ch))
        {
            if (nextCharHandled == false)
            {
                currentChunk = nextChunk;
                currentLine = nextLine;

                switch (currentChunk)
                {
                    case SqlScriptChunkTypes.InstructionOrUnquotedIdentifier:

                        if (ch == '[')
                        {
                            currentChunk = nextChunk = SqlScriptChunkTypes.BracketIdentifier;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == '"')
                        {
                            currentChunk = nextChunk = SqlScriptChunkTypes.DblQuotIdentifierOrLiteral;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == '\'')
                        {
                            currentChunk = nextChunk = SqlScriptChunkTypes.QuotIdentifierOrLiteral;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == '-' && (_isNextChar && _nextChar == '-'))
                        {
                            nextCharHandled = true;
                            currentChunk = nextChunk = SqlScriptChunkTypes.CommentLine;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == '/' && (_isNextChar && _nextChar == '*'))
                        {
                            nextCharHandled = true;
                            currentChunk = nextChunk = SqlScriptChunkTypes.CommentMultiline;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == ']')
                        {
                            throw new SqlBadSyntaxException("Incorrect syntax near ']'.", _lineEnd + lineCounter, _filePath);
                        }
                        else if (ch == '*' && (_isNextChar && _nextChar == '/'))
                        {
                            throw new SqlBadSyntaxException("Incorrect syntax near '*'.", _lineEnd + lineCounter, _filePath);
                        }
                        break;

                    case SqlScriptChunkTypes.CommentLine:

                        if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
                        {
                            nextCharHandled = true;
                            currentChunk = nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                            currentLine = nextLine = lineCounter;
                        }
                        else if (ch == '\n' || ch == '\r')
                        {
                            currentChunk = nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                            currentLine = nextLine = lineCounter;
                        }
                        break;

                    case SqlScriptChunkTypes.CommentMultiline:

                        if (ch == '*' && (_isNextChar && _nextChar == '/'))
                        {
                            nextCharHandled = true;
                            nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                            nextLine = lineCounter;
                        }
                        else if (ch == '/' && (_isNextChar && _nextChar == '*'))
                        {
                            throw new SqlBadSyntaxException("Missing end comment mark '*/'.", _lineEnd + currentLine, _filePath);
                        }
                        break;

                    case SqlScriptChunkTypes.BracketIdentifier:

                        if (ch == ']')
                        {
                            nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                            nextLine = lineCounter;
                        }
                        break;

                    case SqlScriptChunkTypes.DblQuotIdentifierOrLiteral:

                        if (ch == '"')
                        {
                            if (_isNextChar && _nextChar == '"')
                            {
                                nextCharHandled = true;
                            }
                            else
                            {
                                nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                                nextLine = lineCounter;
                            }
                        }
                        break;

                    case SqlScriptChunkTypes.QuotIdentifierOrLiteral:

                        if (ch == '\'')
                        {
                            if (_isNextChar && _nextChar == '\'')
                            {
                                nextCharHandled = true;
                            }
                            else
                            {
                                nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
                                nextLine = lineCounter;
                            }
                        }
                        break;
                }
            }
            else
                nextCharHandled = false;

            foundGO = false;
            if (currentChunk == SqlScriptChunkTypes.InstructionOrUnquotedIdentifier || go >= 5 || (go == 4 && currentChunk == SqlScriptChunkTypes.CommentLine))
            {
                // go = 0 - break, 1 - begin of the string, 2 - spaces after begin of the string, 3 - G or g, 4 - O or o, 5 - spaces after GO, 6 - line comment after valid GO
                switch (go)
                {
                    case 0:
                        if (ch == '\r' || ch == '\n')
                            go = 1;
                        break;
                    case 1:
                        if (ch == ' ' || ch == '\t')
                            go = 2;
                        else if (ch == 'G' || ch == 'g')
                            go = 3;
                        else if (ch != '\n' && ch != '\r')
                            go = 0;
                        break;
                    case 2:
                        if (ch == 'G' || ch == 'g')
                            go = 3;
                        else if (ch == '\n' || ch == '\r')
                            go = 1;
                        else if (ch != ' ' && ch != '\t')
                            go = 0;
                        break;
                    case 3:
                        if (ch == 'O' || ch == 'o')
                            go = 4;
                        else if (ch == '\n' || ch == '\r')
                            go = 1;
                        else
                            go = 0;
                        break;
                    case 4:
                        if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
                            go = 5;
                        else if (ch == '\n' || ch == '\r')
                            foundGO = true;
                        else if (ch == ' ' || ch == '\t')
                            go = 5;
                        else if (ch == '-' && (_isNextChar && _nextChar == '-'))
                            go = 6;
                        else
                            go = 0;
                        break;
                    case 5:
                        if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
                            go = 5;
                        else if (ch == '\n' || ch == '\r')
                            foundGO = true;
                        else if (ch == '-' && (_isNextChar && _nextChar == '-'))
                            go = 6;
                        else if (ch != ' ' && ch != '\t')
                            throw new SqlBadSyntaxException("Incorrect syntax was encountered while parsing go.", _lineEnd + lineCounter, _filePath);
                        break;
                    case 6:
                        if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
                            go = 6;
                        else if (ch == '\n' || ch == '\r')
                            foundGO = true;
                        break;
                    default:
                        go = 0;
                        break;
                }
            }
            else
                go = 0;

            if (foundGO)
            {
                if (ch == '\r' || ch == '\n')
                {
                    ++lineCounter;
                }
                // clear GO
                string s = line.Append(ch).ToString();
                for (int i = 0; i < s.Length; i++)
                {
                    switch (s[i])
                    {
                        case ' ': continue;
                        case '\t': continue;
                        case '\r': continue;
                        case '\n': continue;
                        default:
                            _lineStart = _lineEnd;
                            _lineEnd += lineCounter;
                            return allLines.Append(s.Substring(0, i)).ToString();
                    }
                }
                return string.Empty;
            }

            // accumulate by string
            if (ch == '\r' && (_isNextChar == false || _nextChar != '\n'))
            {
                ++lineCounter;
                if (syntaxCheck == false)
                    allLines.Append(line.Append('\r').ToString());
                line.Clear();
            }
            else if (ch == '\n')
            {
                ++lineCounter;
                if (syntaxCheck == false)
                    allLines.Append(line.Append('\n').ToString());
                line.Clear();
            }
            else
            {
                if (syntaxCheck == false)
                    line.Append(ch);
            }
        }

        // this is the end of the stream, return it without GO, if GO exists
        switch (currentChunk)
        {
            case SqlScriptChunkTypes.InstructionOrUnquotedIdentifier:
            case SqlScriptChunkTypes.CommentLine:
                break;
            case SqlScriptChunkTypes.CommentMultiline:
                if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
                    throw new SqlBadSyntaxException("Missing end comment mark '*/'.", _lineEnd + currentLine, _filePath);
                break;
            case SqlScriptChunkTypes.BracketIdentifier:
                if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
                    throw new SqlBadSyntaxException("Unclosed quotation mark [.", _lineEnd + currentLine, _filePath);
                break;
            case SqlScriptChunkTypes.DblQuotIdentifierOrLiteral:
                if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
                    throw new SqlBadSyntaxException("Unclosed quotation mark \".", _lineEnd + currentLine, _filePath);
                break;
            case SqlScriptChunkTypes.QuotIdentifierOrLiteral:
                if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
                    throw new SqlBadSyntaxException("Unclosed quotation mark '.", _lineEnd + currentLine, _filePath);
                break;
        }

        if (go >= 4)
        {
            string s = line.ToString();
            for (int i = 0; i < s.Length; i++)
            {
                switch (s[i])
                {
                    case ' ': continue;
                    case '\t': continue;
                    case '\r': continue;
                    case '\n': continue;
                    default:
                        _lineStart = _lineEnd;
                        _lineEnd += lineCounter + 1;
                        return allLines.Append(s.Substring(0, i)).ToString();
                }
            }
        }

        _lineStart = _lineEnd;
        _lineEnd += lineCounter + 1;
        return allLines.Append(line.ToString()).ToString();
    }

    bool ReadChar(out char ch)
    {
        if (_isNextChar)
        {
            ch = _nextChar;
            if (_sr.EndOfStream)
                _isNextChar = false;
            else
                _nextChar = Convert.ToChar(_sr.Read());
            return true;
        }
        else if (_sr.EndOfStream == false)
        {
            ch = Convert.ToChar(_sr.Read());
            if (_sr.EndOfStream == false)
            {
                _isNextChar = true;
                _nextChar = Convert.ToChar(_sr.Read());
            }
            return true;
        }
        else
        {
            ch = '\0';
            return false;
        }
    }

    public static int ExecuteSqlFile(string filePath, SqlConnection connection, Encoding fileEncoding, int commandTimeout)
    {
        int rowsAffected = 0;
        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            // Simple syntax check (you can comment out these two lines below)
            new SqlStatementReader(new StreamReader(fs, fileEncoding)).LightSyntaxCheck();
            fs.Seek(0L, SeekOrigin.Begin);

            // Read statements without GO
            SqlStatementReader rd = new SqlStatementReader(new StreamReader(fs, fileEncoding));
            string stmt;
            while ((stmt = rd.ReadStatement()) != null)
            {
                using (SqlCommand cmd = connection.CreateCommand())
                {
                    cmd.CommandText = stmt;
                    cmd.CommandTimeout = commandTimeout;
                    int i = cmd.ExecuteNonQuery();
                    if (i > 0)
                        rowsAffected += i;
                }
            }
        }
        return rowsAffected;
    }
}

0

मुझे जावा में एक ही समस्या थी और मैंने इसे थोड़ा तर्क और रेगेक्स के साथ हल किया। मेरा मानना ​​है कि एक ही तर्क लागू किया जा सकता है। मैं स्मृति में slq फ़ाइल से पढ़ा। फिर मैं निम्नलिखित तर्क लागू करता हूं। यह बहुत ज्यादा है जो पहले कहा जा चुका है लेकिन मेरा मानना ​​है कि रेगेक्स शब्द का उपयोग करना एक नई लाइन चार की अपेक्षा सुरक्षित है।

String pattern = "\\bGO\\b|\\bgo\\b";

String[] splitedSql = sql.split(pattern);
for (String chunk : splitedSql) {
  getJdbcTemplate().update(chunk);
}

यह मूल रूप से sql स्ट्रिंग को वर्ग स्ट्रिंग के एक सरणी में विभाजित करता है। रेगेक्स मूल रूप से पूर्ण 'गो' शब्दों का पता लगाने के लिए या तो निचला मामला या ऊपरी मामला है। फिर आप अलग-अलग क्वेरी को क्रमिक रूप से निष्पादित करते हैं।


1
सावधान: आप इसे कैसे विभाजित करेंगे? insert into books values ('1478355824', 'An Introduction To Programming in Go (paperback)', 9.00)
Blorgbeard

अच्छा बिंदु :-) मेरी स्थिति में डेटा का आवेषण नहीं था। सिर्फ तालिकाओं, संग्रहीत प्रक्रियाओं और कार्यों का निर्माण कर रहा था। बाध्य शब्द मेरे विशेष मामले में अधिक उपयोगी था क्योंकि इसमें अंतिम पंक्ति में 'गो' का भी ध्यान रखा गया था।
जुबेरोडोमिंगस

0

मैंने इसी मुद्दे को मारा और अंततः इसे केवल एक साधारण स्ट्रिंग द्वारा प्रतिस्थापित किया गया, शब्द को प्रतिस्थापित करते हुए GO को अर्ध-बृहदान्त्र के साथ ();

इन-लाइन टिप्पणियों, ब्लॉक टिप्पणियों और GO कमांड के साथ स्क्रिप्ट निष्पादित करते समय सभी ठीक काम कर रहे हैं

public static bool ExecuteExternalScript(string filePath)
{
    using (StreamReader file = new StreamReader(filePath))
    using (SqlConnection conn = new SqlConnection(dbConnStr))
    {
        StringBuilder sql = new StringBuilder();

        string line;
        while ((line = file.ReadLine()) != null)
        {
            // replace GO with semi-colon
            if (line == "GO")
                sql.Append(";");
            // remove inline comments
            else if (line.IndexOf("--") > -1)
                sql.AppendFormat(" {0} ", line.Split(new string[] { "--" }, StringSplitOptions.None)[0]);
            // just the line as it is
            else
                sql.AppendFormat(" {0} ", line);
        }
        conn.Open();

        SqlCommand cmd = new SqlCommand(sql.ToString(), conn);
        cmd.ExecuteNonQuery();
    }

    return true;
}

1
यह DDL कमांड के लिए काम नहीं करेगा, जिसे अपने बैच में होना चाहिए। जैसे टेबल एट अल बनाएं / बदल दें
ब्लोर्बर्ड

इसके अलावा, आप बिना किसी कारण के टिप्पणियों को हटाते हैं .. जो कि किसी भी तार को तोड़ देगा --, उदाहरण के लिए।
ब्लोगर्बर्ड

हाय Blorgbeard - SQL सर्वर 2012 DDL स्टेटमेंट को ठीक करता हुआ प्रतीत होता है। मैं जिन लिपियों का उपयोग कर रहा था, वे मुझे एक संपूर्ण डेटाबेस संरचना के पुनर्निर्माण की अनुमति देने, वर्तमान संरचना को पोंछने, तालिकाओं का निर्माण करने, अनुक्रमणिका जोड़ने आदि के बारे में सोचते थे; एक बैच भी खत्म कर दिया?
मोरवेल 13

टिप्पणियों को हटाने का भी कारण था क्योंकि यह एसक्यूएल की एक पंक्ति का उत्पादन करेगा, इसलिए टिप्पणी के बाद किसी भी एसक्यूएल को टिप्पणी नहीं की जाएगी, लेकिन मैं आपकी बात लेता हूं अगर कोई स्ट्रिंग थी जिसमें निहित था - वह एक टिप्पणी नहीं थी।
Morvael

1
आह ठीक है, बस इसे देखा: "क्रिएट डिफाल्ट, क्रिएट फंक्शन, क्रिएट प्रॉसीड्योर, क्रिएट रूट, क्रिएट स्कीमा, क्रीज ट्राइगर, और क्रिएट व्यू स्टेटमेंट्स को एक बैच में अन्य स्टेटमेंट्स से नहीं जोड़ा जा सकता। क्रिएट स्टेटमेंट को बैच शुरू करना चाहिए। उस बैच में अनुसरण करने वाले अन्य कथनों की व्याख्या पहले क्रिएट स्टेटमेंट की परिभाषा के हिस्से के रूप में की जाएगी। एक तालिका को बदला नहीं जा सकता और फिर उसी बैच में संदर्भित नए कॉलम। "
Blorgbeard

-1

किसी के लिए अभी भी समस्या है। आप आधिकारिक Microsoft SMO का उपयोग कर सकते हैं

https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/overview-smo?view=sql-server-2017

using (var connection = new SqlConnection(connectionString))
{
  var server = new Server(new ServerConnection(connection));
  server.ConnectionContext.ExecuteNonQuery(sql);
}

यह शीर्ष मतदान, स्वीकृत उत्तर पर कुछ भी नहीं जोड़ता है, जो एसएमओ का सुझाव भी देता है (10 साल पहले पोस्ट!)।
ब्लोर्बर्ग 21

-4

बहुत कठिन :)

स्ट्रिंग्स की सरणी बनाएं str [] गो की जगह ", @":

            string[] str ={
                @"
USE master;
",@"


CREATE DATABASE " +con_str_initdir+ @";
",@"
-- Verify the database files and sizes
--SELECT name, size, size*1.0/128 AS [Size in MBs] 
--SELECT name 
--FROM sys.master_files
--WHERE name = N'" + con_str_initdir + @"';
--GO

USE " + con_str_initdir + @";
",@"

SET ANSI_NULLS ON
",@"
SET QUOTED_IDENTIFIER ON
",@"

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Customers]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Customers](
    [CustomerID] [int] IDENTITY(1,1) NOT NULL,
    [CustomerName] [nvarchar](50) NULL,
 CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED 
(
    [CustomerID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
",@"



SET ANSI_NULLS ON
",@"
SET QUOTED_IDENTIFIER ON
",@"
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GOODS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[GOODS](
    [GoodsID] [int] IDENTITY(1,1) NOT NULL,
    [GoodsName] [nvarchar](50) NOT NULL,
    [GoodsPrice] [float] NOT NULL,
 CONSTRAINT [PK_GOODS] PRIMARY KEY CLUSTERED 
(
    [GoodsID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
",@"
SET ANSI_NULLS ON
",@"
SET QUOTED_IDENTIFIER ON
",@"
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Orders]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Orders](
    [OrderID] [int] IDENTITY(1,1) NOT NULL,
    [CustomerID] [int] NOT NULL,
    [Date] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED 
(
    [OrderID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
",@"
SET ANSI_NULLS ON
",@"
SET QUOTED_IDENTIFIER ON
",@"
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OrderDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OrderDetails](
    [OrderID] [int] NOT NULL,
    [GoodsID] [int] NOT NULL,
    [Qty] [int] NOT NULL,
    [Price] [float] NOT NULL,
 CONSTRAINT [PK_OrderDetails] PRIMARY KEY CLUSTERED 
(
    [OrderID] ASC,
    [GoodsID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
",@"

SET ANSI_NULLS ON
",@"
SET QUOTED_IDENTIFIER ON
",@"
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertCustomers]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
create PROCEDURE [dbo].[InsertCustomers]
 @CustomerName nvarchar(50),
 @Identity int OUT
AS
INSERT INTO Customers (CustomerName) VALUES(@CustomerName)
SET @Identity = SCOPE_IDENTITY()

' 
END
",@"
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Orders_Customers]') AND parent_object_id = OBJECT_ID(N'[dbo].[Orders]'))
ALTER TABLE [dbo].[Orders]  WITH CHECK ADD  CONSTRAINT [FK_Orders_Customers] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[Customers] ([CustomerID])
ON UPDATE CASCADE
",@"
ALTER TABLE [dbo].[Orders] CHECK CONSTRAINT [FK_Orders_Customers]
",@"
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_OrderDetails_GOODS]') AND parent_object_id = OBJECT_ID(N'[dbo].[OrderDetails]'))
ALTER TABLE [dbo].[OrderDetails]  WITH CHECK ADD  CONSTRAINT [FK_OrderDetails_GOODS] FOREIGN KEY([GoodsID])
REFERENCES [dbo].[GOODS] ([GoodsID])
ON UPDATE CASCADE
",@"
ALTER TABLE [dbo].[OrderDetails] CHECK CONSTRAINT [FK_OrderDetails_GOODS]
",@"
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_OrderDetails_Orders]') AND parent_object_id = OBJECT_ID(N'[dbo].[OrderDetails]'))
ALTER TABLE [dbo].[OrderDetails]  WITH CHECK ADD  CONSTRAINT [FK_OrderDetails_Orders] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
ON UPDATE CASCADE
ON DELETE CASCADE
",@"
ALTER TABLE [dbo].[OrderDetails] CHECK CONSTRAINT [FK_OrderDetails_Orders]


                "};


            for(int i =0; i<str.Length;i++)     
            {
                myCommand.CommandText=str[i];
                try
                {
                myCommand.ExecuteNonQuery();
                }
                catch (SystemException ee)
                {
                    MessageBox.Show("Error   "+ee.ToString());
                }

            }

बस इतना ही, आनंद लें।

हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.