DB - Day6

Variables

1. Local Variables

It's Considered Local on the scope of batch or function or SP

DECLARE @x int

To Assign Value

SET @x =10
SELECT @x = 9
SELECT @X = age 
	FROM student
	WHERE id = 7
UPDATE student  
	SET name = 'Ali' ,@x=age
WHERE id = 8

Display

SELECT @x

2. Global Variables

We Can't define global variable and can't assign values to it. Only Can Get Values from it it's built in variables

Examples:


Examples

Local Variables

When query return more than one value the variable will only keep the last value


Table Variable

Array of Integer or 1D Array

Table Variable or 2D Array


Dynamic Queries


Control Of Flow Statements

IF

BEGIN END

Used to define scope of if and else


IF EXISTS & IF NOT EXISTS

IF any result it executes query if not execute some other query

Like If Exists but reversed


Begin Try & Begin Catch

If any error happened Execute the catch


WHILE

CONTINUE BREAK


CASE IIF

IIF is like the ternary Operator takes a condition and two options


Windowing Function

Get values from one row before and one row after

Group by the course Name

Display the first and last values from the row


Functions

Built-In Functions

Null

ISNULL() COLEASE()

Conversion

CONVERT() CAST() FORMAT()

System

db_name()

Aggregate

MIN() MAX() AVG() COUNT()

String

CONCAT() UPPER() LOWWER() SUBSTRING()

Date

GETDATE() YEAR() MONTH() DAY() DATEDIFF()

Logical

ISDATE() ISNUMERIC()

Ranking

ROW_NUMBER()


User Defined Functions

All Functions Must Return

Scalar Function

Scalar Functions Return One Value

Call

you must call scalar function with the schema name


Inline Table Value Function

Return Table If only select statement If you make calculation on any column you must give it alias name

Call


Multi-statement Table valued function

Return Table Select or if or while or declaring variable insert based on select

Call


Last updated