Thursday, September 30, 2010

copying text file values as a database column values

Step 1   :   create a table name as login...

Step 2   :

BULK INSERT login FROM 'c:\test_sql.txt' WITH
(
FIELDTERMINATOR = ',',--Data format in text file is username,password in a row.it is used to trminate the symbol comma and assume as a 2 column values

ROWTERMINATOR = '\n' )    --for next line
GO

--Showing the Result
SELECT *
FROM login
GO

Wednesday, September 22, 2010

Stored procedure for finding number days in month

Finding number of days in a month

alter procedure no_of_days as
Declare @no_of_days int
Declare @prev_month varchar(100)
Declare @current_month varchar(100)
Declare @file_duration varchar(100)
DECLARE @returnDate INT
declare @days int

SET @returnDate = CASE WHEN MONTH(getdate())
IN (1, 3, 5, 7, 8, 10, 12) THEN 31
WHEN MONTH(getdate()) IN (4, 6, 9, 11) THEN 30
ELSE CASE WHEN (YEAR(getdate()) % 4 = 0
AND
YEAR(getdate()) % 100 != 0)
OR
(YEAR(getdate()) % 400 = 0)
THEN 29
ELSE 28 END
END

Get previous month name and current month name

set @no_of_days=@returnDate
set @prev_month=(Select Datename(mm, GetDate()-@no_of_days))
set @current_month=(Select Datename(mm, GetDate()))
set @file_duration=@prev_month+'-'+@current_month

Monday, September 13, 2010

Code for Copying Sql Table data into Excel file

Step 1:

Before run this procedure u have to create a excel template file with the relevant column name of the table.

Step 2:

Create PROCEDURE SP_Sql_Excel @File_Name as varchar(50) = ''
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @Dos_Command varchar(1000)
    DECLARE @reportname varchar(500)
    DECLARE @Oledb_provider varchar(100)
    DECLARE @Excel_String varchar(100)

--    New File Name to be created
    IF @File_Name = ''
        Select @reportname = 'C:\temp\Excel\Template1.xls'
    ELSE
        Select @reportname = 'C:\temp\Excel\' + @File_Name + '.xls'

--    FileCopy command string formation
    SELECT @Dos_Command = 'Copy C:\temp\Excel\Template1.xls ' + @reportname

--    Execute Dos Copy command
    EXEC MASTER..XP_CMDSHELL @Dos_Command, NO_OUTPUT

--    Mentioning the OLEDB povider and excel destination filename
    set @Oledb_provider = 'Microsoft.Jet.OLEDB.4.0'
    set @Excel_String = 'Excel 8.0;Database=' + @reportname

--    Executing the OPENROWSET Command for copying the sql data  contents to Excel sheet.
exec('insert into OPENrowset (''' + @Oledb_provider + ''',''' + @Excel_String + ''',''SELECT username,password FROM [Sheet1$]'') select username,password from login')

SET NOCOUNT OFF
END



Step 3:

Run the Procedure


Exec SP_Sql_Excel 'filename'