RSS

Working with SQL Cursors

- The Cursors are used to loop through the Result of SQL Statement.
- This Bellow example shows how to create and loop through the Resulted temp table.


CREATE TABLE #temp
(
name VARCHAR(20),
Salary MONEY
)
INSERT
INTO #temp VALUES
(
'Siva',
20000
)
INSERT
INTO #temp VALUES
(
'Babu',
25000
)
INSERT
INTO #temp VALUES
(
'Raghu',
15000
)
SELECT *
FROM #temp
GO
-- Declaring the Variables to hold the Values
DECLARE @EMPNAME VARCHAR(20) ;
DECLARE @Salary MONEY;
-- Declaring the cursor for accessing the Resulted Records.
DECLARE @NameCursor
CURSOR
-- To refering the Selected values for the cursour
SET @NameCursor=
CURSOR FOR
SELECT NAME,
SALARY
FROM #temp
-- To Open the Cursor and Fetch the Record and Assign to variables
OPEN @NameCursor
FETCH NEXT
FROM @NameCursor
INTO @EMPNAME,
@Salary
-- Loop through the entire Result based on the Resultset
WHILE @@FETCH_STATUS=0
BEGIN
-- Print the Result as you like
PRINT @EMPNAME +'''s Salary:' + CAST(@Salary AS VARCHAR(10))
FETCH NEXT
FROM @NameCursor
INTO @EMPNAME,
@Salary
END
-- Close the cursor
CLOSE @NameCursor
-- Deallocate cursor
DEALLOCATE @NameCursor
--Result
--------
Siva's Salary:20000.00
Babu's Salary:25000.00
Raghu's Salary:15000.00

read comments Read User's Comments

Listing the Available Tables in a DB

We can list the Tables of the Database using SYS.TABLES.


USE TEST
GO
SELECT *
FROM sys.Tables
GO

read comments Read User's Comments

Bulk Insert in SQL Server 2005

In SQL Server 2005 the Bulk Insert is the special Sql statement to insert the bulk data of CSV or another type of files
with field separator character(i.e,; or ^ or , or . separator).

Syntax for Bulk insert:


USE Test
GO
CREATE TABLE USER
(
ID INT ,
FirstName VARCHAR(40),
LastName VARCHAR(40),
BirthDate SMALLDATETIME
)
GO
BULK
INSERT USER
FROM 'F:\User.txt'WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO

Example Script Available for Bulk Insert and Shell Command for getting Files List as Table and upload the files to Database(i.e .dcnlog type files).Click Here to Download...

read comments Read User's Comments