Monday, April 4, 2016

SQL Tutorial In Urdu - Temporary Table And Table Variable (SQL Server)



-- Temporary Table
CREATE TABLE #StudentData (Id INT, Gender NVARCHAR(50))

INSERT INTO #StudentData (Id, Gender)
SELECT [StudentId], [Gender]
FROM [dbo].[Students]

SELECT COUNT(Id) AS Total
  , Gender
FROM #StudentData
GROUP BY Gender

DROP TABLE #StudentData

-- Table Variable
DECLARE @StudentData TABLE (Id INT, Gender NVARCHAR(50))

INSERT INTO @StudentData (Id, Gender)
SELECT [StudentId], [Gender]
FROM [dbo].[Students]

SELECT COUNT(Id) AS Total
  , Gender
FROM @StudentData
GROUP BY Gender

-- Real World Example (Find Total Students Pass and Fail)
SELECT COUNT(StudentId) AS Total
  ,Gender
 FROM [dbo].[Students]
 GRoup by Gender


 -- Temporary Table
 CREATE TABLE #StudentInfo (Id INT, Result NVARCHAR(50))

 INSERT INTO #StudentInfo (Id, Result)
 SELECT StudentId
  , CASE WHEN [StudentTotal] < 300 THEN 'Fail' ELSE 'Pass' END AS Result
  FROM [dbo].[StudentResults]

SELECT COUNT(Id) AS Total
  ,Result
FROM #StudentInfo
GROUP BY Result

DROP TABLE #StudentInfo

 -- Table Variable
 Declare @StudentInfo TABLE (Id INT, Result NVARCHAR(50))

 INSERT INTO @StudentInfo (Id, Result)
 SELECT StudentId
  , CASE WHEN [StudentTotal] < 300 THEN 'Fail' ELSE 'Pass' END AS Result
  FROM [dbo].[StudentResults]

SELECT COUNT(Id) AS Total
  ,Result
FROM @StudentInfo
GROUP BY Result

No comments:

Post a Comment