Friday, 18 July 2014

Difference Between Temporary Table and Table Variable – Summary


Both Temporary Tables (a.k.a # Tables) and Table Variables (a.k.a @ Tables) in Sql Server provide a mechanism for Temporary holding/storage of the result-set for further processing.
Below table lists out some of the major difference between Temporary Table and Table Variable. Each of these differences are explained in-detail with extensive list of examples in the next articles in this series which are listed above.
1. SYNTAX
Below is the sample example of Creating a Temporary Table, Inserting records into it, retrieving the rows from it and then finally dropping the created Temporary Table.
-- Create Temporary Table
CREATE TABLE #Customer
(Id INT, Name VARCHAR(50))
--Insert Two records
INSERT INTO #Customer
VALUES(1,'Basavaraj')
INSERT INTO #Customer
VALUES(2,'Kalpana')
--Reterive the records
SELECT * FROM #Customer
--DROP Temporary Table
DROP TABLE #Customer
GO

Below is the sample example of Declaring a Table Variable, Inserting records into it and retrieving the rows from it.
-- Create Table Variable
DECLARE @Customer TABLE
(
 Id INT,
 Name VARCHAR(50)  
)
--Insert Two records
INSERT INTO @Customer
VALUES(1,'Basavaraj')
INSERT INTO @Customer
VALUES(2,'Kalpana')
--Reterive the records
SELECT * FROM @Customer
GO
RESULT:
2. MODIFYING STRUCTURE
Temporary Table structure can be changed after it’s creation it implies we can use DDL statements ALTER, CREATE, DROP.
Below script creates a Temporary Table #Customer, adds Address column to it and finally the Temporary Table is dropped.
--Create Temporary Table
CREATE TABLE #Customer
(Id INT, Name VARCHAR(50))
GO
--Add Address Column
ALTER TABLE #Customer
ADD Address VARCHAR(400)
GO
--DROP Temporary Table
DROP TABLE #Customer
GO
Table Variables doesn’t support DDL statements like ALTER, CREATE, DROP etc, implies we can’t modify the structure of Table variable nor we can drop it explicitly.
3. STORAGE LOCATION
One of the most common MYTH about Temporary Table & Table Variable is that: Temporary Tables are created in TempDB and Table Variables are created In-Memory. Fact is that both are created in TempDB, below Demos prove this reality.
4. TRANSACTIONS
Temporary Tables honor the explicit transactions defined by the user.Table variables doesn’t participate in the explicit transactions defined by the user.
5. USER DEFINED FUNCTION
Temporary Tables are not allowed in User Defined Functions.Table Variables can be used in User Defined Functions.
6. INDEXES
Temporary table supports adding Indexes explicitly after Temporary Table creation and it can also have the implicit Indexes which are the result of Primary and Unique Key constraint.Table Variables doesn’t allow the explicit addition of Indexes after it’s declaration, the only means is the implicit indexes which are created as a result of the Primary Key or Unique Key constraint defined during Table Variable declaration.
7. SCOPE
There are two types of Temporary Tables, one Local Temporary Tables whose name starts with single # sign and other one is Global Temporary Tables whose name starts with two # signs.Scope of the Local Temporary Table is the session in which it is created and they are dropped automatically once the session ends and we can also drop them explicitly. If a Temporary Table is created within a batch, then it can be accessed within the next batch of the same session. Whereas if a Local Temporary Table is created within a stored procedure then it can be accessed in it’s child stored procedures, but it can’t be accessed outside the stored procedure.Scope of Global Temporary Table is not only to the session which created, but they will visible to all other sessions. They can be dropped explicitly or they will get dropped automatically when the session which created it terminates and none of the other sessions are using it.Scope of the Table variable is the Batch or Stored Procedure in which it is declared. And they can’t be dropped explicitly, they are dropped automatically when batch execution completes or the Stored Procedure execution completes.
Sqlhints

Function For Amount Conversion From Number to Word In Sql Server ...

Create FUNCTION [dbo].[Fn_numtowords]
(
@Param1 numeric(30,2)
)
RETURNS varchar(max)
AS
BEGIN
Declare @Ndec numeric(10,2)
Declare @NRet varchar(max)
Declare @NRetDec varchar(max)
Set @NRetDec=''
If @Param1 <> 0
Begin
Select @Ndec = @Param1  % convert( integer, floor(@Param1) )
Select @NRet = dbo.udf_Num_ToWords(convert( integer, floor(@Param1) ) )
End

--If Isnull( @Ndec ,0) <> 0
If @Param1 <> 0
Select @NRetDec = ' And ' +dbo.udf_Num_ToWords(@Ndec * 100 ) + ' Fils Only'
Else
 Select @NRetDec = 'Zero' 

Friday, 11 July 2014

Navigate From One Report to another report(Linked Report)



="javascript:void(window.open('http://isplsvr4/ReportServer/Pages/ReportViewer.aspx?%2feCompliance%2fAdmin%2fTest1&rs:Command=Render&UserCode="+Fields!UserCode.Value+"','popup', 'status=no,scrollbars=no,toolbar=no,location=no,menubar=no,resizable=yes','_blank'))"

Monday, 23 June 2014

Removing weekends and Bank Holidays (Dubai) from TSQL SELECT with a function


Alter FUNCTION dbo.fn_WorkDays (@StartDate AS DATETIME, @EndDate AS DATETIME)
--Define the output data type.
RETURNS INT
AS
--Calculate the RETURN of the function.
BEGIN
    RETURN (
     SELECT
        (DATEDIFF(dd,@StartDate, @EndDate)+1)--Start with total number of days including weekends +1 Includes the day run
        -(DATEDIFF(wk,@StartDate, @EndDate)*2)--Subtact 2 days for each full weekend
        -(CASE WHEN DATENAME(dw, @StartDate) = 'Friday' --If StartDate is a Sunday, Subtract 1
            THEN 1
            ELSE 0
        END)
        -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'--If EndDate is a Saturday, Subtract 1
            THEN 1
            ELSE 0
        END)
        --Now check if there are any bank holidays between the start and end and remove that amount
        - (SELECT COUNT(ivm.HolidayDate)
          FROM Holiday ivm
          WHERE ivm.HolidayDate BETWEEN @StartDate AND @EndDate
          AND  (DatePart(dw, HolidayDate) != 1) and (DatePart(dw, HolidayDate) != 7))
          --WHERE ivm.[Date] BETWEEN '2006-04-14' AND '2006-05-29')    
)
 END
GO

Monday, 16 June 2014

Company Sql Server

XL Health 16-06-2014
-------------------------------------
Q1) Select 1
     union
    Select 2
    Union
    Select 1 As ID
   Union
   Select 2 As ID,
   Union All
    Select 3


O/p=1
        2
        3

q2)
------------------------------
ID    NAme                     Amount      Total AMount
1 Reddy                100.00 100.00
2 SubbareddyReddy 200.00 300.00
3 OmReddy                600.00 900.00
5 Test                      100.00 1000.00
6 Test                       100.00 1100.00


Solution Is:

Select CID,CName,
Amount,
(Select Sum(Amount) From AutoSum S  where S.CID < A.CID+1 ) As Balance
From AutoSum A

Tuesday, 10 June 2014

Get Quarters StartDate and EndDate from Year

CREATE FUNCTION cal_quarter (@DATE SMALLDATETIME)

    RETURNS INT
    AS
BEGIN
declare @CalendarQuarter int
        IF month(@DATE) in(4,5,6)
            BEGIN
                set @CalendarQuarter =1
            END
        if month(@DATE) in(7,8,9)
            BEGIN
                set @CalendarQuarter =2
            END
        if month(@DATE) in(10,11,12)
            BEGIN
                set @CalendarQuarter =3
            END
        if month(@DATE) in(1,2,3)
            BEGIN
                set @CalendarQuarter =4
            END
return @CalendarQuarter
END