Creating Temporary Variables
Creating Temporary Variables
Integer numbers
-- Initialise a variable, give it a data type and an initial value
DECLARE @myvar as smallint = 2000
-- Multiply that variable by 10
SET @myvar = @myvar * 10
-- Retrieve that variable
SELECT @myvar AS myVariable
--BITS
--Bigint
--Int - up to 2,000,000,000
--Tinyint - 0-255
--Smallint - -32767 to 32768
Non-integer numbers
-- Initialise a variable, give it a data type and an initial value
GO
GO
Page 1
70-461 Session 1: Querying Microsoft SQL Server 2012
© Filecats Limited 2015
For the full course, go to www.udemy.com
GO
Mathematical functions
--Initialise a variable, give it a data type and an initial value
SELECT POWER(@myvar,3) -- 27
SELECT SQUARE(@myvar) -- 9
SELECT POWER(@myvar,0.5) -- square root of 3
SELECT SQRT(@myvar) -- square root of 3
GO
GO
SELECT ABS(@myvar) as myABS, SIGN(@myvar) as mySign -- This equals 456 and -1.
GO
SELECT @myvar
-- explicit
SELECT CONVERT(decimal(5,2),3)/2
Page 2
70-461 Session 1: Querying Microsoft SQL Server 2012
© Filecats Limited 2015
For the full course, go to www.udemy.com
Strings
-- char - ASCII - 1 byte
-- varchar - ASCII - 1 byte
-- nchar - UNICODE - 2 bytes
-- nvarchar - UNICODE - 2 bytes
String Functions
DECLARE @chrASCII as varchar(10) = 'hellothere'
NULL – an introduction
declare @myvar as int
Page 3
70-461 Session 1: Querying Microsoft SQL Server 2012
© Filecats Limited 2015
For the full course, go to www.udemy.com
SELECT 'My salary is: $' + convert(varchar(20),2345.6) -- works , but not well
SELECT 'My salary is: ' + format(2345.6,'C','fr-FR')
Page 4
70-461 Session 1: Querying Microsoft SQL Server 2012
© Filecats Limited 2015
For the full course, go to www.udemy.com
Date offsets
declare @myDateOffset as datetimeoffset(2) = '2015-06-25 01:02:03.456 +05:30' -- 8-10
bytes
select @myDateOffset as MyDateOffset
go
declare @myDate as datetime2 = '2015-06-25 01:02:03.456'
select TODATETIMEOFFSET(@myDate,'+05:30') as MyDateOffset
Page 5