Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

sql server query output to json file automatically

// TODO: Add your code here
                string query = "SELECT TOP 5 [BusinessEntityID],[NationalIDNumber],[OrganizationNode],[OrganizationLevel] FROM [HumanResources].[Employee]";
                string connectionSql = "Server=(local);Database=AdventureWorks2016CTP3;Integrated Security=true";
                StreamWriter myFile = new StreamWriter(@"c:sqlfileCSharp.txt");
                using (SqlConnection connection = new SqlConnection(connectionSql))
                {
                    SqlCommand command = new SqlCommand(query, connection);
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    try
                    {
                        while (reader.Read())
                        {
                            myFile.WriteLine(String.Format("{0}, {1}, {2}, {3}", 
                            reader["BusinessEntityID"], reader["NationalIDNumber"], reader["OrganizationNode"], reader["OrganizationLevel"]));
                        }
                    }
                    catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                            Dts.TaskResult = (int)ScriptResults.Failure;
                        }
                    finally
                        {
                            reader.Close();
                            myFile.Close();
                        }
                }
Source by www.sqlservercentral.com #
 
PREVIOUS NEXT
Tagged: #sql #server #query #output #json #file #automatically
ADD COMMENT
Topic
Name
7+2 =