Thursday, December 29, 2011

Script to calculate the Median value for SQL Server data

--Script to calculate the Median value for SQL Server dataDECLARE
SET
WITH
AS(SELECT ROW_NUMBER() OVER (ORDER BY PRODUCTID) AS ROW ,* FROM SALESLT.PRODUCT --its important to speciafy actuall column name in order by caluse as for the result)SELECT
WHERE ROW = @MIDDLE
* FROM RESULT
RESULT
@MIDDLE = (SELECT ROUND(COUNT(*)*0.5,0) FROM SALESLT.PRODUCT);
@MIDDLE INT

Creting User Define DataType

--How to create User Define DataType with Default and Rules

--Creating Default
CREATE
AS 'UnknownNumber' -- this is default value when no value is specifiedGO

--Creating RuleCreate
AS
(@phone='UnknownNumber') or (len(@phone) = 14 and substring(@phone,1,1) = '+' and substring(@phone,5,1) = '-')--Rule says when there is no value it place 'UnknownNumber'
--or lenght should be of 14 number and number should begin with '+' and '-' after 3rd digit to identify the state code

--Creting User Define DataType
EXEC SP_ADDTYPE --Sp to create datatypePhoneNumber, -- Name of new user defined data type that is being created'varchar(25)', -- Base system data type of SQL Server'not null', -- To specify that null values are allowed for this data type or not'dbo' -- Owner of this being created user defined data type
Rule Rule_Phn
DEFAULT Default_Phn