Basic T-SQL in MS SQL Server

What is T-SQL ? 
T-SQL stand for Transact SQL.T-SQL is procedural SQL database programming language, is powerful language offering many features to produce query to interact with database.
In this post, I would like to share some syntax with examples of T-SQL.

  • How to declare variable in stored procedure
  • How to set value of variable
  • How to convert DataType
1.  How to declare variable in stored procedure
     You can declare variable in stored procedure as syntax below:

Syntax:
         + Declare single variable
               Declare @variable_name DataType
                    Example : Declare @datein Date; 
         + Declare multiple variables
               Declare @variable_name1 DataType , @variable_name2  DataType , @variable_name3 DataType;
               Example: Declare @datein Date ,@cateid int,@countryid int;

2. How to set value of variable
     You can assign value to variable as the way below:
     Syntax: Set @variable_name = value 
        Example:  set @proid = 2
                     set @userid =(select userid from tbluser where name='Tharoth')
3. How to convert DataType

       There are two ways to convert DataType. Please see syntax below:
      Syntax 1:  Cast(Variable as DataType)
     Syntax 2:  Convert(DataType , @variable)
     Example : Convert from int DataType to Varchar DataType. Please exmin code below: 
        Code:
       --Declare variables
       Declare @x int, @y int, @result1 varchar(10),@result2 varchar(10)

   --convert variable with CAST keyword
   set @result1= CAST((@x+@y) as varchar(10))

--convert variable with CONVERT keyword
      set @result2 =CONVERT(varchar(10), @x + @y

Done...Let's fun with it
Basic T-SQL in MS SQL Server Basic T-SQL in MS SQL Server Reviewed by BeiLover on 2:30 PM Rating: 5

1 comment:

Powered by Blogger.