Pages

Friday 29 March 2013

How to create duplicate table with new name in SQL Server 2008


How to create duplicate table with new name in SQL Server 2008

or How to copy or backup table

SELECT *
INTO new_table_name 
FROM old_tablename
Or we can select only the columns we want into the new table:
SELECT column_name(s)
INTO new_table_name 
FROM old_tablename
Example :
SELECT *
INTO Employee_Backup
FROM Employee
only columns:
SELECT LastName,FirstName
INTO Employee_Backup
FROM Employee

Thursday 14 March 2013

Disable your back button


Code to disable your back button on logout page after logging out from page:

Place this code just above the head section of your master page source code(which contains your logout button) and/or also on a page wherever your logout button is placed.

<script type = "text/javascript" >
function disableBackButton() {
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>

Find Nth Highest Salary of Employee



The following solution is for getting 6th highest salary from Employee table ,

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP 6 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

You can change and use it for getting nth highest salary from Employee table as follows

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP n salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary
where n > 1 (n is always greater than one)

Wednesday 6 March 2013

SQL Server Basics of Cursors

Cursor is a database objects to retrieve data from a result set one row at a time, instead of the T-SQL commands that operate on all the rows in the result set at one time.
We use cursor when we need to update records in a database table in singleton fashion means row by row.
Life Cycle of Cursor:
Declare Cursor:
Syntax:
DECLARE cursor_name CURSOR
FOR select_statement --define SQL Select statement
FOR UPDATE [col1,col2,...coln] --define columns that need to be updated
Open Cursor:
Syntax:
OPEN [GLOBAL] cursor_name --by default it is local
Fetch Cursor:
Syntax:
INTO @Variable_name[1,2,..n]
Close Cursor
Syntax:
CLOSE cursor_name --after closing it can be reopen
Deallocate Cursor
Syntax:
DEALLOCATE cursor_name --after deallocation it can't be reopen

An Example of Cursor:

create PROCEDURE sp_rohit
AS  
BEGIN
declare @empCode as varchar(30)
declare @emp_name as varchar(100)

--start cursor for check employee
DECLARE rohit_cursor cursor
for select empcode, emp_name from master_employee

OPEN rohit_cursor
/* first fetch starts the process */
FETCH rohit_cursor  INTO @empCode ,@emp_name
WHILE @@fetch_status = 0 /* while there's still records to process */
BEGIN
                        print @emp_name 
                        FETCH rohit_cursor  INTO @empCode ,@emp_name
                        end
close rohit_cursor
DEALLOCATE rohit_cursor
--end this cursor
end --end store procedure