简体   繁体   中英

Sql Stored Procedure to csv file with Timestamp

The application stores results from a SQL stored procedure into a given csv. It is necessary for the file to have a timestamp within the filename. I haven't been successful finding the solution through any of my research. Here's the code, keep in mind that the timestamp needs to have the date and most importantly the time 'hh:ss'

string db = "databasename";
        string startTime = "2018-04-17 00:00:00.000";
        string endTime = "2018-04-17 23:59:59.997";
        string LiquorFile = "LiquorFile.csv";

        using (SqlConnection con = new SqlConnection(GlobalConfig.CnnString(db)))
        {
            var tableName = "liqTemp";
            var fileName = tableName + ".csv";
            var recordCount = 0;
            var fileCount = 0;

            SqlCommand scCmd = new SqlCommand("dbo.spGetInventory_Liquor", con);
            scCmd.CommandType = CommandType.StoredProcedure;
            SqlDataReader reader;

            con.Open();

            scCmd.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startTime;
            scCmd.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = endTime;

            reader = scCmd.ExecuteReader();

            StreamWriter writer = null;

            try
            {
                while (reader.Read())
                {
                    if (writer == null || recordCount == 50000)
                    {
                        if (writer != null)
                        {
                            writer.Close();
                            writer.Dispose();
                        }
                        fileName = tableName + "_" + (++fileCount).ToString() + ".csv";

                        writer = new StreamWriter(fileName);
                    }
                    recordCount++;
                    writer.WriteLine("\t{0}\t{1}", reader.GetDecimal(0), reader.GetString(1));
                }
                reader.NextResult();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Dispose();
                }
            }
        }

Brainstorming through this implementation I believe this can be incorporated somehow through the start and end time string.

I'm still thinking of a proper title for this question.

Appears that you want to store some metadata along with the raw CSV data. Some file types, depending on the file type, have loads of metadata properties like authorship and company name etc. So, in this situation, I might elect to store my CSV data in XSLX format using the amazing ClosedXML library. The XSLX file type has lots of metadata properties to store your timestamps and many more.

Below is an example adding properties to a Docx file. This just shows that Microsoft office formats have lots of available metadata properties you can access and use.
How to set extended file properties?

using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;

string filePath = @"C:\temp\example.docx";
var file = ShellFile.FromFilePath(filePath);

// Read and Write:

string[] oldAuthors = file.Properties.System.Author.Value;
string oldTitle = file.Properties.System.Title.Value;

file.Properties.System.Author.Value = new string[] { "Author #1", "Author #2" };
file.Properties.System.Title.Value = "Example Title";

// Alternate way to Write:

ShellPropertyWriter propertyWriter =  file.Properties.GetPropertyWriter();
propertyWriter.WriteProperty(SystemProperties.System.Author, new string[] { "Author" });
propertyWriter.Close();

Think its just a simple use of current date formatting.

fileName = tableName + "_" + DateTime.Today.ToString("yyyyMMddHHmmss") + ".csv";

where the format is whatever you need - date, time, ticks, etc - whatever you need to get the granularity you desire. You can go to a formt string of "o" to get it down to decimal sub-seconds if you need to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM