Showing posts with label Datatypes. Show all posts
Showing posts with label Datatypes. Show all posts

Monday, 14 September 2015

How to use the user defined datatype in Table creation ?

In SQL server ,while table creation we can use the SQL server datatype to create columns and also possible to use our own user data type.

If you are going to use the same data type with same length for your entire project ,then we can create our own user defined datatype and use it .

Now we will use our created datatype which is created in our previous post (Refer Here).

Create Table dbo.Student 
(
       StudentID Int Not Null,
       Name Varchar(50) Not Null,
       Department UserType 
)


Now we have used our created datatype in the above table. So the user datatype will be very helpful in this kind of scenario.


What is user defined datatype in sql server and how to create ?

In SQL server ,we can create our own userdatatype and can be used while table creation.

Create Syntax :

CREATE TYPE [TYPE NAME] FROM [DATE TYPE] [NULL | NOT NULL CONSTRAINT]

Example:

CREATE TYPE  UserType FROM NVARCHAR(10) NULL

Now the type named "UserType" is created as NVARCHAR datatype and it is nullable column.

Drop Syntax :

DROP TYPE [TYPE NAME]

DROP TYPE UserType

we can also add the type using System SP.

Create Syntax :

EXEC SP_ADDTYPE [TYPE NAME],[DATA TYPE(LENGTH)],[NULL | NOT NULL CONSTRAINT]

Example:

Exec Sp_AddType 'UserType','Nvarchar(10)','Null'

Its also possible to alter the type using the following syntax.

Alter Syntax : 

EXEC SP_RENAME [EXISTING TYPE NAME],[NEW TYPE NAME],[USERDATETYPE]

Example: 

Exec Sp_Rename 'UserType','UserTypeName','USERDATATYPE'

Sunday, 13 September 2015

List of Datatypes in SQL server with Precedence

In SQL server all the datatypes are executed based on the precedence.
The datatype with highest precedence will be executed first and with lower precedence will be executed next.

Please find the list of datatypes used in sql server.

  1. user-defined data types (highest)
  2. sql_variant
  3. xml
  4. datetimeoffset
  5. datetime2
  6. datetime
  7. smalldatetime
  8. date
  9. time
  10. float
  11. real
  12. decimal
  13. money
  14. smallmoney
  15. bigint
  16. int
  17. smallint
  18. tinyint
  19. bit
  20. ntext
  21. text
  22. image
  23. timestamp
  24. uniqueidentifier
  25. nvarchar (including nvarchar(max) )
  26. nchar
  27. varchar (including varchar(max) )
  28. char
  29. varbinary (including varbinary(max) )
  30. binary (lowest)