0% found this document useful (0 votes)
82 views

TSQL

The document discusses T-SQL and stored procedures in SQL Server. It covers T-SQL concepts like functions, procedures, indexes and transactions. It also discusses SQL Server data types, variables, and how to declare, assign values to, and use variables in T-SQL code. The document provides examples of IF/ELSE conditional logic and loops like WHILE in T-SQL stored procedures to calculate factorial, Fibonacci series, and other examples.

Uploaded by

Monu Mishra
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

TSQL

The document discusses T-SQL and stored procedures in SQL Server. It covers T-SQL concepts like functions, procedures, indexes and transactions. It also discusses SQL Server data types, variables, and how to declare, assign values to, and use variables in T-SQL code. The document provides examples of IF/ELSE conditional logic and loops like WHILE in T-SQL stored procedures to calculate factorial, Fibonacci series, and other examples.

Uploaded by

Monu Mishra
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

T-Sql

• T-SQL (Transact-SQL) is an extension of SQL language. This


tutorial covers the fundamental concepts of T-SQL such as its
various functions, procedures, indexes, and transactions related
to the topic. Each topic is explained using examples for easy
understanding.
• SQL Server data type is an attribute that specifies types of data
of any object. Each column, variable and expression has related
data type in SQL Server. These data types can be used while
creating tables. You can choose a particular data type for a
table column based on your requirement.
• SQL Server offers seven categories including other category of
data types for use
Variable
• Types of Variable: Local, Global
• MS SQL has two types of variables:
1.Local variable
2.Global variable.
• Local variable:
• A user declares the local variable.
• By default, a local variable starts with @.
• Every local variable scope has the restriction to the current batch or
procedure within any given session.
• Global variable:
• The system maintains the global variable. A user cannot declare
them.
• The global variable starts with @@
• It stores session related information.
How to DECLARE a variable

• Before using any variable in batch or procedure, you need


to declare the variable.
• DECLARE command is used to DECLARE variable which acts as a
placeholder for the memory location.
• Only once the declaration is made, a variable can be used in the
subsequent part of batch or procedure.
TSQL Syntax:

DECLARE { @LOCAL_VARIABLE[AS] data_type [ = value ] }

Rules:

• Initialization is an optional thing while declaring.


• By default, DECLARE initializes variable to NULL.
• Using the keyword 'AS' is optional.
• To declare more than one local variable, use a comma after the first local variable definition,
• and then define the next local variable name and data type.
Examples of Declaring a variable:

Query: With 'AS'

DECLARE @COURSE_ID AS INT;

Query: Without 'AS'

DECLARE @COURSE_NAME VARCHAR (10);

Query: DECLARE two variables

DECLARE @COURSE_ID AS INT, @COURSE_NAME VARCHAR (10);


Assigning a value to a VARIABLE
You can assign a value to a variable in the following three ways:

• During variable declaration using DECLARE keyword.


• Using SET
• Using SELECT
During variable declaration using DECLARE keyword.

• T-SQL Syntax:

• DECLARE { @Local_Variable [AS] Datatype [ = value ] }


• Here, after datatype we can use '=' followed by value to be assigned

• Query:

• DECLARE @COURSE_ID AS INT = 5


• PRINT @COURSE_ID
Using SET

• Sometimes we want to keep declaration and initialization separate. SET can


be used to assign values to the variable, post declaring a variable.Below are
the different ways to assign values using SET:

• Example: Assigning a value to a variable using SET

• Syntax:

• DECLARE @Local_Variable <Data_Type>


• SET @Local_Variable = <Value>
• Query:

• DECLARE @COURSE_ID AS INT


• SET @COURSE_ID = 5
• PRINT @COURSE_ID
Example: Assign a value to multiple variables using SET.

• Syntax:

• DECLARE @Local_Variable _1 <Data_Type>, @Local_Variable_2


<Data_Type>,
• SET @Local_Variable_1 = <Value_1>
• SET @Local_Variable_2 = <Value_2>
• Rule: One SET Keyword can be used to assign a value to only one
variable.
• Query:

• DECLARE @COURSE_ID as INT, @COURSE_NAME AS VARCHAR(5)


• SET @COURSE_ID = 5
• SET @COURSE_NAME = 'UNIX'
• PRINT @COURSE_ID
• PRINT @COURSE_NAME
USING SELECT

• Just like SET, we can also use SELECT to assign values to the variables, post
declaring a variable using DECLARE. Below are different ways to assign a value
using SELECT:

• Example: Assigning a value to a variable using SELECT

• Syntax:

• DECLARE @LOCAL_VARIABLE <Data_Type>


• SELECT @LOCAL_VARIABLE = <Value>
• Query:

• DECLARE @COURSE_ID INT


• SELECT @COURSE_ID = 5
• PRINT @COURSE_ID

• DECLARE @SName varchar(30);


SELECT @SName = S_NAME FROM STUDENTS WHERE STUDENT_ID = 191;
print @SName;
Assigning a value to multiple variable using SELECT

• Syntax:

• DECLARE @Local_Variable _1 <Data_Type>, @Local_Variable _2


<Data_Type>,SELECT @Local_Variable _1 = <Value_1>,
@Local_Variable _2 = <Value_2>
• Rules: Unlike SET, SELECT can be used to assign a value to multiple
variables separated by the comma.
If -else
If (cond)
BEGIN
Statements
END
Else
BEGIN
Statements
END
Programming eaxmples
• DECLARE @radius AS INT =2;
DECLARE @Pi AS INT =3.14;

declare @Area int = @pi*@radius*@radius;


PRINT 'Area=' + CAST(@Area AS VARCHAR);
• DECLARE @C AS INT = 50;

DECLARE @F AS FLOAT = (@C*9)/5 + 32;

PRINT 'TEMPRATURE IN FARENHEIT = ' + CAST(@F AS VARCHAR);


• DECLARE @marks AS INT,@count int;

• SELECT @marks = SUM(MARKS),@count=COUNT(sid) FROM


STUDENTS where cgpa<5;

• DECLARE @prec AS INT = @marks/@count;


• PRINT 'Average marks for Students = ' + CAST(@prec AS varchar);
• DECLARE @A AS INT = 69;
DECLARE @B AS INT = 78;
PRINT 'A before swpping = ' + CAST(@A AS VARCHAR)+char(10);
PRINT 'B before swapping= ' + CAST(@B AS VARCHAR)+char(13);
DECLARE @Swap AS INT = @A;
SET @A = @B;
SET @B = @Swap;
PRINT 'A after swpping= ' + CAST(@A AS VARCHAR);
PRINT 'B after swapping= ' + CAST(@B AS VARCHAR);
• DECLARE @x AS INT =1;
DECLARE @y AS INT =2;

if(@x>@y)
print ' X is Greater than y';
else
print'Y is Greater than x';
• DECLARE @G AS INT = 34;

IF(@G%2 = 0)
BEGIN
PRINT 'NUMBER IS EVEN';
END

ELSE
BEGIN
PRINT 'NUMBER IS ODD';
END
• declare @avgCGPA int, @studCGPA int;
• select @avgCGPA= avg(CGPA)from Students;
• select @studCGPA = CGPA from Students where STUDENT_ID=101;
• print @studCGPA;
• print @avgCGPA;
• if(@studCGPA> @avgCGPA)
• Begin
• print 'Abc has more CGPA then the average CGPA of students’;
• End
• Else
• BEGIN
• print'Student has more CGPA than the average CGPA of abc’;
• END
Declare @total int;
select @total= sum(P_price*QTY) from product;
Print @total;
if (@total>50000)
BEGIN
select * from product where discount<1000;
END
else
BEGIN
select * from product where discount>1000
declare @a int =1;

while @a<=50
BEGIN
if(@a%2==0)
BEGIN
print cast(@a as varchar)+'is even';
END
set @a=@a+1;
END
DECLARE @R int,@REV int=0,@N1 int;
SET @N1 = 28;
WHILE (@N1 > 0)
BEGIN

SET @R = @N1%10;
SET @REV = @REV*10+@R;
SET @N1= @N1/10;
Print 'reverse number is' +cast(@REV as varchar);
END
• ----------------WAP to build 1-5 multiplication table
DECLARE @X INT =1, @PRO INT =1, @I2 INT =1;
WHILE (@X <=5)
Begin

PRINT 'The table of '+ cast(@X as varchar)+ ':'


WHILE (@I2 <= 10)
BEGIN
SET @PRO = @X * @I2;
PRINT cast(@X as varchar) + '*' + cast(@I2 as varchar) + '=' +cast (@PRO as varchar)
Set @I2 = @I2+1;
END

Set @X = @X+1;
set @I2 = 1;
END
create table s_details(id varchar(20),rollno int, section varchar(10));
declare @a int =1;
while @a<=10
BEGIN
insert into s_details values('stu-'+cast((100+@a) AS
varchar),@a,'JK902');
set @a=@a+1;
END
• CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;
• SELECT OrderID, Quantity,
CASE
    WHEN Quantity > 30 THEN 'The quantity is
greater than 30'
    WHEN Quantity = 30 THEN 'The quantity is 30'
    ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;
Case statements
• Update stu_details
• Set branch=
• Case Branch
• when 'CSE' then 'Computer '
• when 'Electrical' then 'Electro'
• else 'Civil'

• End
• update Students
set BRANCH= Case Branch
when 'CSE' then 'Computer Science'
when 'Electrical' then'Electronics'
when 'Polytechnic' then 'Chemical Engg'
End
select * from Students;
• CASE
•     WHEN ComparsionCondition THEN result
•     WHEN ComparsionCondition THEN result
•     ELSE other
• END
• select cust_name,age,gender from customer2 order by

• case WHEN GENDER ='Female' THEN age END desc,


• case WHEN GENDER ='male'
• THEN age
• end
stored procedure
• A stored procedure is a prepared SQL code that you can save, so the
code can be reused over and over again.

• So if you have an SQL query that you write over and over again, save it
as a stored procedure, and then just call it to execute it.
Benefits of using a stored procedure

• It can be easily modified: We can easily modify the code inside the stored procedure without the
need to restart or deploying the application. For example, If the T-SQL queries are written in the
application and if we need to change the logic, we must change the code in the application and re-
deploy it. SQL Server Stored procedures eliminate such challenges by storing the code in the database.
so, when we want to change the logic inside the procedure we can just do it by simple ALTER
PROCEDURE statement.
• Reduced network traffic: When we use stored procedures instead of writing T-SQL queries at the
application level, only the procedure name is passed over the network instead of the whole T-SQL
code.
• Reusable: Stored procedures can be executed by multiple users or multiple client applications without
the need of writing the code again.
• Security: Stored procedures reduce the threat by eliminating direct access to the tables. we can also
encrypt the stored procedures while creating them so that source code inside the stored procedure is
not visible. Use third-party tools like ApexSQL Decrypt to decrypt the encrypted stored procedures.
• Performance: The SQL Server stored procedure when executed for the first time creates a plan and
stores it in the buffer pool so that the plan can be reused when it executes next time.
• CREATE PROCEDURE procedure_name
• AS
• sql_statement
• GO;

• EXEC procedure_name;
• CREATE PROCEDURE p11
AS
BEGIN
DECLARE @A INT=0, @B INT=1, @C INT=0, @D INT=0
PRINT'Fibonacci Series'
Print @a
print @b
WHILE @D<18
BEGIN
SET @C=@A+@B
PRINT @C
SET @D=@D+1
SET @A=@B
SET @B=@C
END
END
GO
EXEC P11;
• CREATE PROCEDURE p6
AS
BEGIN
DECLARE @I INT=1,@R INT =1,@N INT =5
WHILE(@I<=@N)
BEGIN
SET @R=@R*@I
SET @I+=1
END
PRINT @R
END
GO
EXEC P6;
• CREATE PROCEDURE Multi @X INT
AS
DECLARE @PRO INT =1, @I2 INT =1;

PRINT 'The table of '+ cast(@X as varchar)+ ':'


WHILE (@I2 <= 10)
BEGIN
SET @PRO = @X * @I2;
PRINT cast(@X as varchar) + '*' + cast(@I2 as varchar) + '=' +cast (@PRO as varchar)
Set @I2 = @I2+1;
END

go
• CREATE PROCEDURE Factorialof7 @N int
as
declare @fact int =1, @i int =1;
while (@i<=@N)

begin
set @fact= @fact * @i
set @i= @i+1

end

print 'The factorial of 7 is:'


print @fact
go
EXEC Factorialof7 @N =7
• CREATE PROCEDURE calculator1 @A AS INT, @B AS VARCHAR(5), @C AS VARCHAR
AS
BEGIN
DECLARE @out INT = 1
BEGIN
IF(@B = '+')
SET @out = @A + @C;
ELSE IF(@B='-')
SET @out = @A - @C;
ELSE
SET @out = @A * @C;
END
PRINT @out
END
GO
EXEC calculator1 1,'+',2;
• CREATE PROCEDURE calculator1 @d as int = 19, @e as int =83, @f as int =7
AS
print'Displaying all the arithmetic oprations: ';

print'Addition: ';
---------declare @d as int = 19, @e as int =83, @f as int =7 ;
declare @add int = @d+@e+@f;
print 'The Sum is: ' + cast (@add as varchar);

print'Subtraction: ';
--------declare @s as int =83, @t as int =7 ;
declare @sub int = @e - @d - @f;
print 'The difference is: ' + cast (@sub as varchar);

print'Multiplication: ';
---declare @x as int = 19, @y as int =83, @z as int =7 ;
declare @Product int = @e* @f * @d;
print 'The Product is: ' + cast (@Product as varchar);

go
exec calculator1 @d =19, @e =83, @f =7 ;
• 11
Create procedure proc1 @limit int
AS BEGIN
select * from products where price>@limit order by QTY exec proc1
2000
• alter proc1 products who are having price more than the min price but
less than the max
create PROCEDURE ProPrice @m1 as int ,@m2 as int
AS
BEGIN
select P_id, P_Name, P_Price, Qty from Product where P_Price >@m1 AND P_price<@m2
END
declare @m3 as int, @m4 as int
select @m3= min(P_price) from Product
select @m4= max(P_price) from Product

exec ProPrice @m3, @m4;


create a procedure to get the deatils of customer whose salesman
have a certain commision value which must be passed as a
parameter
• CREATE PROCEDURE Commission @com as int
AS
select C.CUST_NAME,S.Sales_man_Name from Customer2 AS C
INNER JOIN SALESMAN AS S ON C.Salesman_Id=S.SALESMAN_ID
where S.Commission> @com;

go
exec Commission @com =100;
• https://sqlserverguides.com/advanced-stored-procedure-examples-
in-sql-server/

You might also like