Translate

Friday, 19 July 2013

Rollup table, aggregate function, CTE

CTE

CTE stands for Common Table expressions. It was introduced with SQL Server 2005. It is a temporary result set and typically it may be a result of complex sub-query. Unlike temporary table its life is limited to the current query. It is defined by using WITH statement. CTE improves readability and ease in maintenance of complex queries and sub-queries. Always begin CTE with semicolon.

A sub query without CTE is given below :

  1. SELECT * FROM (
  2. SELECT Addr.Address, Emp.Name, Emp.Age From Address Addr
  3. Inner join Employee Emp on Emp.EID = Addr.EID) Temp
  4. WHERE Temp.Age > 50
  5. ORDER BY Temp.NAME

By using CTE above query can be re-written as follows :

  1. ;With CTE1(Address, Name, Age)--Column names for CTE, which are optional
  2. AS
  3. (
  4. SELECT Addr.Address, Emp.Name, Emp.Age from Address Addr
  5. INNER JOIN EMP Emp ON Emp.EID = Addr.EID
  6. )
  7. SELECT * FROM CTE1 --Using CTE
  8. WHERE CTE1.Age > 50
  9. ORDER BY CTE1.NAME

When to use CTE

  1. This is used to store result of a complex sub query for further use.
  2. This is also used to create a recursive query.

    Table Variable

    This acts like a variable and exists for a particular batch of query execution. It gets dropped once it comes out of batch. This is also created in the Tempdb database but not the memory. This also allows you to create primary key, identity at the time of Table variable declaration but not non-clustered index.
    1. GO
    2. DECLARE @TProduct TABLE
    3. (
    4. SNo INT IDENTITY(1,1),
    5. ProductID INT,
    6. Qty INT
    7. )
    8. --Insert data to Table variable @Product
    9. INSERT INTO @TProduct(ProductID,Qty)
    10. SELECT DISTINCT ProductID, Qty FROM ProductsSales ORDER BY ProductID ASC
    11. --Select data
    12. Select * from @TProduct
    13. --Next batch
    14. GO
    15. Select * from @TProduct --gives error in next batch

    Note

    1. Temp Tables are physically created in the Tempdb database. These tables act as the normal table and also can have constraints, index like normal tables.
    2. CTE is a named temporary result set which is used to manipulate the complex sub-queries data. This exists for the scope of statement. This is created in memory rather than Tempdb database. You cannot create any index on CTE.
    3. Table Variable acts like a variable and exists for a particular batch of query execution. It gets dropped once it comes out of batch. This is also created in the Tempdb database but not the memory.


--------------------------
create table tbl_test (iid int identity(1,1),strname varchar(300), iValue int )



insert into tbl_test(strname,ivalue) values('E',12)


select strname,SUM(ivalue) value into #temp from tbl_test group by strname  with cube
declare @iper int
select @iper=value from #temp where strname is null
select strname,iValue,sum(Convert(decimal(9,2),(Convert(decimal(9,2) , iValue)/Convert(decimal(9,2),@iper))*100)) 'percentage' into #temp1 from tbl_test
group by strname,iValue


;WITH cte AS
(
SELECT strname name,iValue,percentage,percentage score,ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS row
FROM #temp1
)

select bb.strname,iValue,aa.percentage,aa.score from
(SELECT a.name,a.percentage,SUM(b.score) score
FROM cte a
INNER JOIN cte b ON a.row >=b.row
GROUP BY a.name,a.percentage)aa inner join #temp1 bb on aa.name=bb.strname

Saturday, 6 July 2013

சுண்ட வத்தக்குழம்பு


சுண்ட வத்தக்குழம்பு


தேவையான பொருட்கள் ;
காய்ந்த சுண்ட வத்தல் - ஒரு கைபிடியளவு
நல்ல எண்ணெய் - 100 மில்லி + 2 டேபிள்ஸ்பூன்
முழுமல்லி - 1 டேபிள்ஸ்பூன்
சீரகம் - 1டீஸ்பூன்
மிளகு - அரைடீஸ்பூன்
மிளகாய் வற்றல் - 6-8
கடுகு - கால்ஸ்பூன்
வெந்தயம் - கால்ஸ்பூன்
கடலை பருப்பு- 2 டீஸ்பூன்
உளுத்தம் பருப்பு - 2 டீஸ்பூன்
மிள்காய்த்தூள் - அரைடீஸ்பூன்
புளி - எலுமிச்சை அளவு
பூண்டு பெரிய பல் -3
கருவேப்பிலை - 2 இணுக்கு
உப்பு - தேவைக்கு



முதலில் வெறும் வாணலியில் மல்லி,சீரகம்,மிளகு,கடுகு,வெந்தயம்,கடலை பருப்பு,உளுத்தம் பருப்பு ஆகியவற்றை வறுத்து எடுக்கவும்.ஒரு டீஸ்பூன் எண்ணெய் விட்டு மிளகாய் வற்றலை வறுத்து எடுக்கவும்,அதிலேயே பாதி சுண்டவத்தலை(15-20) வறுத்து எடுத்து அரைக்க எடுத்து வைக்கவும்.பாதியை குழம்பில் போட வைக்கவும்,இதனில் பாதி சுண்ட வத்தலையும் சேர்த்து அரைப்பதால் குழம்பு காரம்,கசப்பு,புளிப்பு என்று சுவை அருமையாக இருக்கும்.



பின்பு அதே வாணலியில் பூண்டு,கருவேப்பிலை வறுத்து அத்துடன் அணைத்து பொருளையும் சேர்த்து ஒரு பிரட்டு பிரட்டி ஆறவைக்கவும்.



புளியை ஊறவைக்கவும்.வறுத்ததை சிறிது தண்ணீர் சேர்த்து அரைத்து எடுக்கவும்.




புளிக்கரைசலோடு அரைத்தவற்றை சேர்த்து கரைத்து தேவைக்கு உப்பு சேர்த்து வைக்கவும்.



வாணலியில் எண்ணெய் விட்டு பாதி சுண்டவத்தலை எண்ணெயில் போட்டு பொரிய விடவும்.


சுண்ட வத்தல் பொரியவும் அரைத்த விழுது புளிக்கரைசலை சேர்க்கவும்.


நன்கு கொதி வரும்,சிம்மில் வைத்து அடிபிடிக்காமல் வற்ற விடவும்.



குழம்பு வற்றி இப்படி வரும்.


குழம்பு சிவப்பாய் பார்க்க அழகாய் இருக்க ஒரு தாளிப்பு கரண்டியில் 2 டேபிள்ஸ்பூன் எண்ணெய் விட்டு காயவும் அரை டீஸ்பூன் மிளகாய்த்தூள் சேர்த்து உடன் ரெடி ஆன வத்தக்குழம்பில் கொட்டி கலந்து விடவும்.நன்கு கலந்து விடவும்.


சுவையான சூப்பரான வத்தக்குழம்பு ரெடி.

Transposing Rows to columns without aggregation and Displaying column header as First column In sql server 2008(pivot)


swap the N rows to columns without aggregation function in sql server 2008

CREATE TABLE testing1(Spot_dt date, Costed INT, celldata INT)

INSERT INTO testing1 (Spot_dt,Costed,celldata) values ('2012-04-08',1,15);
INSERT INTO testing1 (Spot_dt,Costed,celldata) values ('2012-04-15',1,24);
INSERT INTO testing1 (Spot_dt,Costed,celldata) values ('2012-04-22',1,36);

select * from testing1


Spot_dt      Costed celldata
2012-04-08 1           15
2012-04-15 1           24
2012-04-22 1           36

DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX)


select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Spot_dt)
                    from testing1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT valtype dates, ' + @cols + '
              from (select Spot_dt, Costed, CellData from testing1) as x
              unpivot (vals for valtype in (Costed, celldata)) as u
              pivot (min(vals) for spot_dt in (' + @cols + ')) as p'

execute(@query)


dates 2012-04-08 2012-04-15 2012-04-22
CellData     15               24               36
Costed       1                 1                 1



Thursday, 4 July 2013

Tips to improve SQL Server database design and performance


Design Patterns Tutorial - For Beginners & Professionals 

http://www.dotnet-tricks.com/Tutorial/designpatternslist


Tips to improve SQL Server database design and performance

  1. Choose Appropriate Data Type

    Choose appropriate SQL Data Type to store your data since it also helps in to improve the query performance. Example: To store strings use varchar in place of text data type since varchar performs better than text. Use text data type, whenever you required storing of large text data (more than 8000 characters). Up to 8000 characters data you can store in varchar.
  2. Avoid nchar and nvarchar

    Does practice to avoid nchar and nvarchar data type since both the data types takes just double memory as char and varchar. Use nchar and nvarchar when you required to store Unicode (16-bit characters) data like as Hindi, Chinese characters etc.
  3. Avoid NULL in fixed-length field

    Does practice to avoid the insertion of NULL values in the fixed-length (char) field. Since, NULL takes the same space as desired input value for that field. In case of requirement of NULL, use variable-length (varchar) field that takes less space for NULL.
  4. Avoid * in SELECT statement

    Does practice to avoid * in Select statement since SQL Server converts the * to columns name before query execution. One more thing, instead of querying all columns by using * in select statement, give the name of columns which you required.
    1. -- Avoid
    2. SELECT * FROM tblName
    3. --Best practice
    4. SELECT col1,col2,col3 FROM tblName
  5. Use EXISTS instead of IN

    Does practice to use EXISTS to check existence instead of IN since EXISTS is faster than IN.
    1. -- Avoid
    2. SELECT Name,Price FROM tblProduct
    3. where ProductID IN (Select distinct ProductID from tblOrder)
    4. --Best practice
    5. SELECT Name,Price FROM tblProduct
    6. where ProductID EXISTS (Select distinct ProductID from tblOrder)
  6. Avoid Having Clause

    Does practice to avoid Having Clause since it acts as filter over selected rows. Having clause is required if you further wish to filter the result of an aggregations. Don't use HAVING clause for any other purpose.
  7. Create Clustered and Non-Clustered Indexes

    Does practice to create clustered and non clustered index since indexes helps in to access data fastly. But be careful, more indexes on a tables will slow the INSERT,UPDATE,DELETE operations. Hence try to keep small no of indexes on a table.
  8. Keep clustered index small

    Does practice to keep clustered index as much as possible since the fields used in clustered index may also used in nonclustered index and data in the database is also stored in the order of clustered index. Hence a large clustered index on a table with a large number of rows increase the size significantly. Please refer the article Effective Clustered Indexes
  9. Avoid Cursors

    Does practice to avoid cursor since cursor are very slow in performance. Always try to use SQL Server cursor alternative. Please refer the article Cursor Alternative.
  10. Use Table variable inplace of Temp table

    Does practice to use Table varible in place of Temp table since Temp table resides in the TempDb database. Hence use of Temp tables required interaction with TempDb database that is a little bit time taking task.
  11. Use UNION ALL inplace of UNION

    Does practice to use UNION ALL in place of UNION since it is faster than UNION as it doesn't sort the result set for distinguished values.
  12. Use Schema name before SQL objects name

    Does practice to use schema name before SQL object name followed by "." since it helps the SQL Server for finding that object in a specific schema. As a result performance is best.
    1. --Here dbo is schema name
    2. SELECT col1,col2 from dbo.tblName
    3. -- Avoid
    4. SELECT col1,col2 from tblName
  13. Keep Transaction small

    Does practice to keep transaction as small as possible since transaction lock the processing tables data during its life. Some times long transaction may results into deadlocks. Please refer the article SQL Server Transactions Management
  14. SET NOCOUNT ON

    Does practice to set NOCOUNT ON since SQL Server returns number of rows effected by SELECT,INSERT,UPDATE and DELETE statement. We can stop this by setting NOCOUNT ON like as:
    1. CREATE PROCEDURE dbo.MyTestProc
    2. AS
    3. SET NOCOUNT ON
    4. BEGIN
    5. .
    6. .
    7. END
  15. Use TRY-Catch

    Does practice to use TRY-CATCH for handling errors in T-SQL statements. Sometimes an error in a running transaction may cause deadlock if you have no handle error by using TRY-CATCH. Please refer the articleException Handling by TRY…CATCH
  16. Use Stored Procedure for frequently used data and more complex queries

    Does practice to create stored procedure for quaery that is required to access data frequently. We also created stored procedure for resolving more complex task.
  17. Avoid prefix "sp_" with user defined stored procedure name

    Does practice to avoid prefix "sp_" with user defined stored procedure name since system defined stored procedure name starts with prefix "sp_". Hence SQL server first search the user defined procedure in the master database and after that in the current session database. This is time consuming and may give unexcepted result if system defined stored procedure have the same name as your defined procedure.

http://www.dotnet-tricks.com/Tutorial/sqlserver/bM6H260812-Tips-to-improve-SQL-Server-database-design-and-performance.html