Use Sql query to write/create a file

11. December 2009 14:33

SQL Server T-SQL 

This SQL stored procedure will allow you to write to the file on your file system. Note the file system will be the the same on which the SQL server is running. If you are using this with your local SQL server then it will write and create files on your local file system and if you are on the remote machine, the file system will be the remote file system.

Create Procedure  [dbo].[USP_SaveFile](@text as NVarchar(Max),@Filename Varchar(200)) 
AS 
Begin 
 
declare @Object int,
        @rc int, -- the return code from sp_OA procedures 
        @FileID Int 
 
EXEC @rc = sp_OACreate 'Scripting.FileSystemObject', @Object OUT 
EXEC @rc = sp_OAMethod  @Object , 'OpenTextFile' , @FileID OUT , @Filename , 2 , 1 
Set  @text = Replace(Replace(Replace(@text,'&','&'),'<' ,'<'),'>','>')
EXEC @rc = sp_OAMethod  @FileID , 'WriteLine' , Null , @text  
Exec @rc = master.dbo.sp_OADestroy @FileID   
 
Declare @Append  bit
Select  @Append = 0
 
If @rc <> 0
Begin
    Exec @rc = master.dbo.sp_OAMethod @Object, 'SaveFile',null,@text ,@Filename,@Append
       
End

Exec @rc = master.dbo.sp_OADestroy @Object 
    
End 

But before you start using this procedure you need to reconfigure some advanced SQL server settings. Use the below configuration query to enable 'OLE Automation Procedures'. If this is not enabled and you try executing the procedure you will get errors.

Use master
GO
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
--To enable Ole automation feature
EXEC sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO

The first parameter will take the text to be written to the file and the second parameter will take the complete path of the file to be created with the text in it. You can also use the same procedure to wite binary files to the file system, you just need to check and change the file extension in the second parameter. Usage:

EXEC USP_SaveFile 'Microsoft SQL Server 2008', 'C:\MSSQL.txt' 
Currently rated 4.0 by 1 person

T-SQL: Export Table to Excel

2. December 2009 20:31

SQL Server T-SQL 

What you do to export data from SQL to excel. You use data import/export wizard or just simply execute the select query and copy the whole lot of data in an excel file with headers. Copy and paste the data in the excel sheet is the quickest possible solution I can see...but what if you have to data through your code? Still there are many possible ways to accomplish this but how many lines of code you have to write to achieve this? maybe most of the people definately have a simple and reliable way. Ok...lets do this using T-SQL query. The only problem I see here is that you must have a excel file in the location defined in the query before you execute the query.

In one of our application we maintain log in a sql table for all the tasks done in the whole day. The administrator of the application want to take a look at all the tasks done by a particular user, he didn't want any UI to look into this instead he asks us to generate a report at the end of the day in excel on a button click. So lets see the code.

Execute the below query to set the configuration of SQL Server to 1. In my case there was no change as I already executed this query in the past. But, most probably you will see a change in the your case the value could be changed from 0 to 1.

EXEC sp_configure 'show advanced options', 1;
GO RECONFIGURE;
GO EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
GO RECONFIGURE;
GO

After you set the configuration option execute a normal select query to get all the column names and paste them in the excel sheet. Then save the excel sheet in your local hard drive.

Select TOP 0 * From Person.Address

--For Office 2003 (.XLS) format
INSERT INTO OPENROWSET ('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=c:\contact.xls;','SELECT * FROM [Sheet1$]')SELECT * FROM authors

--For Office 2007 (.XLSX) format
INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;Database=c:\contact.xlsx;','SELECT * FROM [Sheet1$]')SELECT * FROM authors
Currently rated 5.0 by 2 people

T-SQL: Recently Executed Query

14. October 2009 05:16

SQL Server T-SQL 

I am a regular reader of Pinal Dave's blog SqlAuthority. I always found something new in his blog to work with SQL Server. Here is something I would like to share: Get the recent executed SQL Queries from SQL Server.

SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
FROM sys.dm_exec_query_stats AS deqs CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle)
AS destORDER BY deqs.last_execution_time DESC
 No Rating

GUIDs in C# / SQL

26. June 2009 15:37

C# SQL Server Code Snippets 

GUID pronounced as goo'id - Globally unique identifier is a 128-bit integer that can be used to uniquely identify something. If you want to identify the large collection of data GUID is the best approach in my view. Also you can use the autoincremental integer to identify records, this is the basic approach programmer's use.

GUID method can be found under the System namespace and it also provides some overloads. Here is how we can use the GUID overloads:

System.Guid.NewGuid().ToString();    //c93ded50-7cce-4f3a-b8aa-5a1a34d80b14
System.Guid.NewGuid().ToString("N"); //636bdfd2bbc541229fbc6b869995ce6f
System.Guid.NewGuid().ToString("D"); //45e602b6-0904-47ac-a764-a5522f56f40f
System.Guid.NewGuid().ToString("B"); //{68f55508-f72c-4a38-b96b-f493c3c5adb9}
System.Guid.NewGuid().ToString("P"); //(1c2e52a7-e384-445e-b80a-e8704c6ecbd6)

To create GUID in SQL Server use the simple select statement:

SELECT NEWID()

 No Rating

Backup/Restore SQL database using C#

21. June 2009 15:59

C# SQL Server Utils 

Microsoft’s .NET framework provides the flexibility to Backup and Restore SQL server database. A few lines to populate the names of all the server instances, create backups and then restore the backups. The application what you see here is a part of an application, so when you create backups and restore it will use the same path hardcoded in the code itself. You can change the way you like it.


Namespace you need to add:  

using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;

I am not going to write on and on and just make it going boring, so it's better just download the code and check the comments, they are one liners, but clears everything. 

Download Full Application Here: DBBackup.zip (290.99 kb)

Currently rated 3.6 by 19 people

«12»