簡體   English   中英

使用 C# 將正確數據放入正確 SQL 列的問題

[英]Issue with putting correct data into correct SQL columns using C#

我編寫了一個代碼,它將讀取一個分隔的 txt 文件,然后解析數據並使用該信息更新 Microsoft SQL 服務器表。

代碼如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FileHelpers;
using System.Data.SqlClient;
using System.IO;
using System.Data;

namespace prototype_using_filehelpers
{

    class ManagerReport
    {

        [DelimitedRecord("|")]
        [IgnoreEmptyLines()]
        [IgnoreFirst()]
        [IgnoreLast(2)]


        public class ManagerReportNames
        {


            public int? MASTER_VALUE_ORDER;
            public int? MASTER_VALUE;
            public string RESORT;
            public int? CS_HEADING_COUNT_MASTER;
            public int? CS_FS_ARR_ROOMS_MASTER;
            public int? CS_FS_DEP_ROOMS_MASTER;
            public int? CS_FS_NO_ROOMS_MASTER;
            public int? CS_FS_GUESTS_MASTER;
            public int? CS_FS_TOTAL_REVENUE_MASTER;
            public int? CS_FS_ROOM_REVENUE_MASTER;
            public int? CS_FS_INVENTORY_ROOMS_MASTER;
            public int? CF_FS_PERC_OCC_ROOMS_MASTER;
            public int? CF_FS_AVG_ROOM_RATE_MASTER;
            public int? LAST_YEAR_01;
            public int? SUB_GRP_1_ORDER;
            public string SUB_GRP_1;
            public string DESCRIPTION;
            public string AMOUNT_FORMAT_TYPE;
            public string PRINT_LINE_AFTER_YN;
            public int? HEADING_1_ORDER;
            public int? HEADING_1;
            [FieldOptional]
            public string HEADING_2;
            [FieldOptional]
            [FieldConverter(ConverterKind.Decimal, ".")]
            public decimal? SUM_AMOUNT;
            [FieldOptional]
            public float? FORMATTED_AMOUNT;


        }

        static void ProcessFilesCSVFiles(string originalPath, string destinationPath)
        {


            // first check if path exists
            if (!Directory.Exists(originalPath))
                // doesn't exist then exit, can't copy from something that doesn't exist
                return;
            var copyPathDirectory = new DirectoryInfo(originalPath);
            // using the SearchOption.AllDirectories will search sub directories
            var copyPathCSVFiles = copyPathDirectory.GetFiles("*.txt", SearchOption.AllDirectories);
            // loops through directory looking for txt files
            for (var i = 0; i < copyPathCSVFiles.Length; i++)
            {
                // get the file
                var csvFile = copyPathCSVFiles[i];
                //sets lines to the files full extention so it can then be called at a later time
                string lines = csvFile.FullName;

                // read the csv file line by line
                FileHelperEngine engine = new FileHelperEngine(typeof(ManagerReportNames));
                var records = engine.ReadFile(lines) as ManagerReportNames[];


                foreach (var record in records)
                {
                    Console.WriteLine(record.RESORT);
                    Console.WriteLine(record.FORMATTED_AMOUNT);
                    // This allows us to split what column a row goes into based on whether it is a day month or year
                    string Heading = record.HEADING_2;
                    string Group = record.SUB_GRP_1;
                    string column;
                    if (Heading == "DAY" && Group == "OCC_PERC")
                    {
                        column = "Percent_Rooms_Occupied";
                    }
                    else if (Heading == "DAY" && Group == "OCC_PERC_WO_CH")
                    {
                        column = "Percent_Rooms_Occupied_minus_Comp_and_House";
                    }
                    else if (Heading == "DAY" && Group == "ADR_ROOM")
                    {
                        column = "ADR";
                    }
                    else if (Heading == "DAY" && Group == "ADR_ROOM_WO_CH")
                    {
                        column = "ADR_minus_Comp_and_House";
                    }
                    else if (Heading == "DAY" && Group == "ROOMREV_AVL_ROOMS_MINUS_OOO")
                    {
                        column = "Revenue_per_Available_Room_minus_OOO";
                    }
                    else if (Heading == "DAY" && Group == "TOTAL_REVENUE")
                    {
                        column = "Total_Revenue";
                    }
                    else if (Heading == "DAY" && Group == "ROOM_REVENUE")
                    {
                        column = "Room_Revenue";
                    }
                    else if (Heading == "DAY" && Group == "FOOD_BEV_REVENUE")
                    {
                        column = "Food_And_Beverage_Revenue";
                    }
                    else if (Heading == "DAY" && Group == "OTHER_REVENUE")
                    {
                        column = "Other_Revenue";

                    }
                    else if (Heading == "DAY" && Group == "PHYSICAL_ROOMS")
                    {
                        column = "Total_Rooms_in_Hotel";

                    }
                    else if (Heading == "DAY" && Group == "OCC_ROOMS")
                    {
                        column = "Rooms_Occupied";

                    }
                    else if (Heading == "DAY" && Group == "OCC_MINUS_COMP_HU")
                    {
                        column = "Rooms_Occupied_minus_Comp_and_House_Use";

                    }
                    else if (Heading == "DAY" && Group == "COMP_ROOMS")
                    {
                        column = "Complimentary_Rooms";

                    }
                    else
                    {
                        column = "";
                    }




                    // SQL connection. Creates connection and command and inserts the values taken from the File Helper engine into the SQL table
                    SqlCommand cmd;
                    SqlConnection conn;


                    conn = new SqlConnection("Data Source=hureports01;Initial Catalog=hureports;Integrated Security=True");
                    conn.Open();
                    var sqlCommand = string.Format(@"MERGE [HEWreport] AS target USING (select @Property_ID as Property_ID, @val as {0}) AS source ON (target.Property_ID = source.Property_ID) WHEN MATCHED THEN UPDATE SET {0}= source.{0}
                                                    WHEN NOT MATCHED THEN INSERT (Property_ID, {0}) VALUES (source.Property_ID, source.{0});", column);
                    cmd = new SqlCommand(sqlCommand, conn);
                    cmd.Parameters.AddWithValue("@Property_ID", record.RESORT);
                    cmd.Parameters.AddWithValue("@val", record.FORMATTED_AMOUNT);
                    cmd.ExecuteNonQuery();
                }




                // creates a variable that combines the the directory of the new folder with the file name
                var destinationFilePath = Path.Combine(destinationPath, csvFile.Name);
                // This loop prevents duplicates. If a file is already in the folder, it will delete the file already in there and move this one in.
                // Shouldn't be an issue since each file will have a different name
                if (File.Exists(destinationFilePath))
                {
                    File.Delete(destinationFilePath);
                }
                // moves it to the new folder
                csvFile.MoveTo(destinationFilePath);


            }
        }


        static void Main(string[] args)
        {

            ProcessFilesCSVFiles(@"C:\Users\btajfel\Documents\Opera\Hotels", @"C:\Users\btajfel\Documents\Opera\Completed Hotels");


        }
    }
}

我只真正關注RESORTHEADING_2SUB_GRP_1FORMATTED_AMOUNT

我想要實現的是在Property_ID下有一行具有RESORT的值,因為來自同一 txt 的所有行都將具有相同的屬性 ID,然后根據HEADING_2SUB_GRP_1的值,包含這些的特定行的FORMATTED_AMOUNT兩個值將進入一列,然后包含HEADING_2SUB_GRP_1的下兩個特定值的行的FORMATTED_AMOUNT將直接進入它旁邊的列。

它適用於Property_ID和第一列,但隨后我在cmd = ExecuteNonQuery()旁邊收到一個錯誤,內容為:

“System.Data.dll 中發生類型為 'System.Data.SqlClient.SqlException' 的未處理異常附加信息:')' 附近的語法不正確。”

我不確定是不是因為我的代碼無法正常工作,或者是我犯了一個小錯誤還是什么。

在偽代碼中:

if (column != "")
{ do your sql command }
else
{ do something else, or do nothing at all }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM