DotNet Friends

October 23, 2009

HierarchyId Data Type

Here I Explained the New Data Type in Sqlserver 2008.

What is HierarchIyd Data Type? 

HierarchyId data type is a variable length System Data Type.

What is the use of HierarchyId Data Type?

Represent position in a hierarchy manner.

HierarchyId does not automatically represent a tree, it is depend on how to application generate and assign HierarchyId values.

HierarchyId have following properties:

1) Extremely Compact

2) Comparison is in depth-first-order.

3) Support for arbitrary insertions and deletions.

Limitation Of HierarchyId :

1)  Does not automatically represent a Tree

2) It is up to Application to manage concurrency in generating and assigning HierarchyId Values.

3) There is no any dependency on HierarchyId relationship.

 

See more about HierarchyId example refer :

http://amitpatriwala.wordpress.com/2009/10/23/sql-server-2008-feature-part1/

Reference Site :

http://technet.microsoft.com/en-us/library/bb677290.aspx

Sql Server 2008 Feature – Part1

Here I am explaining Sql Server 2008 Key Features.

1) Initializing variable when you declare

declare @val as int =0
declare @currentdate as datetime = getdate
()
print @val
print @currentdate

2) Compound assignment operators

–operator like +=,-=,/=,*/,%=
declare @val as int = 0
set @val += 10
;
print @val

3) Add multiple row in single Insert Statement

CREATE TABLE Employee
(
EmpId int,
EmpCode varchar(50),
EmpName varchar(50)
);

INSERT INTO Employee(EmpId, EmpCode,EmpName)
  VALUES
  (1, 'emp1','emp1'),
  (2, 'emp1','emp1'),
  (3, 'emp1','emp1');

select * from Employee
4) New Data Types
Data Type Data Type Use
Date The Date property returns a Date data type.
Time Returns values for any valid time of day between 00:00:00 and 23:59:59:9999999. It has a length of at least 8 positions and contains the time in hours,minutes, seconds and fractional seconds.
DateTime2 DateTime2 is an extension of the existing DATETIME type. It has a large date range and large default fractional precision. It has a length of at least 19 positions.
DateTimeOffSet Returns values for year, month, day, valid time of day between 00:00:00 and 23:59:59:9999999 and offset, in hours, from UTC. It has a length of at least 25 positions.
Hierarchyid The HierarchyId property is used to identify a position in a hierarchy.
Geography The SQL Server geography data type stores ellipsoidal (round-earth) data, such as GPS latitude and longitude coordinates
Geometry The Geometry property contains spatial data that represents information about the physical location and shape of geometric objects.
HierarchyId Data Type
   1: --Create Table Employee

   2: CREATE TABLE Employee

   3: (

   4: EmpId int,

   5: EmpBossId HIERARCHYID,

   6: --GetLevel --> returns the level of the current node in the hierarchy

   7: EmpLevel as EmpBossId.GetLevel() PERSISTED,

   8: EmpCode varchar(50),

   9: EmpName varchar(50)

  10: );

  11: Go

  12: -- Create Insert Store Procedure

  13: Alter PROCEDURE Employee_isp

  14:     @empid int,

  15:     @empbossid int,

  16:     @empcode varchar(50),

  17:     @empname varchar(50)

  18: AS

  19: BEGIN

  20: declare @hid HIERARCHYID,@empboss_hid HIERARCHYID,@last_hid HIERARCHYID

  21:  

  22: if @empbossid = 0 

  23: begin

  24:     set @hid = HIERARCHYID::GetRoot();

  25: end 

  26: else 

  27: begin

  28:   

  29:   SET @empboss_hid = (SELECT EmpBossId FROM Employee  WHERE empid = @empbossid);

  30:   SET @last_hid = (SELECT MAX(EmpBossId) FROM Employee WHERE EmpBossId.GetAncestor(1)= @empboss_hid);

  31:   SET @hid = @empboss_hid.GetDescendant(@last_hid, NULL);

  32: end

  33: INSERT INTO Employee(empid, EmpBossId, EmpCode, EmpName)

  34:             VALUES(@empid, @hid, @empcode, @empname);

  35: END

  36: GO

  37: --insert data

  38: --                     A1

  39: --                AL1           AR1

  40: --           AL1L     AL1R  AR1L   AR1R  

  41: --

  42: --

  43: EXEC Employee_isp @empid =  1, @empbossid = 0, @empcode = 'A1' ,@empname = 'A1';

  44: EXEC Employee_isp @empid =  2, @empbossid = 1, @empcode = 'AL1' ,@empname = 'AL1';

  45: EXEC Employee_isp @empid =  3, @empbossid = 1, @empcode = 'AR1' ,@empname = 'AR1';

  46: EXEC Employee_isp @empid =  4, @empbossid = 2, @empcode = 'AL1L' ,@empname = 'AL1L';

  47: EXEC Employee_isp @empid =  5, @empbossid = 2, @empcode = 'AL1R' ,@empname = 'AL1R';

  48: EXEC Employee_isp @empid =  6, @empbossid = 3, @empcode = 'AR1L' ,@empname = 'AR1L';

  49: EXEC Employee_isp @empid =  7, @empbossid = 3, @empcode = 'AR1R' ,@empname = 'AR1R';

Inserted Data Into Table 
HIERARCHYID 
Different Selection Criteria :
1) Find Employee As Per their Level means Grade 
   select * from Employee where Emplevel = 2
2) Get Child Node 
   SELECT Child.empid, Child.empname FROM Employee AS Parent JOIN Employee AS Child
          ON Parent.empid = 2 AND child.empbossid.IsDescendantOf(Parent.empbossid) = 1;
3) Get Parent Node
SELECT parent.empid, parent.empname
  FROM Employee AS Parent JOIN Employee AS Child
    ON child.empid = 4 AND child.empbossid.IsDescendantOf(Parent.empbossid) = 1;
more on HierarchyId Data Types refer:
http://amitpatriwala.wordpress.com/2009/10/23/hierarchyid-data-type/

5) Introduced New Functions
Function Name Function Use
SYSDATETIME Returns current date and time as DateTime2 value.
SYSUTCDATETIME Returns current date and time in UTC as DateTime2 value
SYSDATETIMEOFFSET Returns current date and time along with the system time zone as a DATETIMEOFFSET value
SWITCHOFFSET Adjusts an input DATETIMEOFFSET value to a specified time zone, while preserving the UTC value.

For example, the following code adjusts the current system datetimeoffset value to time zone GMT +05:00:

SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), ‘-05:00′);

TODATETIMEOFFSET sets the time zone offset of an input date and time value
6) Support Large User Define Types [UDT]
Sql Server 2008 supports large UDT,large UDTs can now reach up to 2 GB in size.
 
Reference Sites: 
http://technet.microsoft.com/en-us/library/cc721270.aspx

October 11, 2008

Get Parameter List from StoreProcedure or Function in SqlServer 2005

–get all storeprocedure and function

SELECT * FROM INFORMATION_SCHEMA.PARAMETERS

–pass storeprocedure name or function name

–get the relavent columns ParameterName,DataType,Length,ParameterType

SELECT Parameter_name as ParameterName,Data_type as DataType,coalesce(Character_Maximum_Length,0) as Length,Parameter_Mode as ParameterType FROM INFORMATION_SCHEMA.PARAMETERS

WHERE SPECIFIC_NAME=’sp_InsertOrder’

Get Primary key – Foreign key relations table in sql server 2005

Why it is required?

The main purpose of this is finding related constraint table from database.

Check below Query.

–get table list with constraint(primary and foreign key)

select * from information_schema.constraint_column_usage

–get table list with foreign key constraint

select * from information_schema.referential_constraints

–get the relation

select

tblAll.table_name as PrimaryTableName,

tblAll.column_name as PrimaryTableColumn,

tblFK.table_name as ForeignKeyTable,

tblFK.column_name as ForeignKeyColumn

from information_schema.constraint_column_usage tblAll

inner join information_schema.referential_constraints tblAllFK on tblAllFK.unique_constraint_name = tblAll.constraint_name

inner join information_schema.constraint_column_usage tblFK on tblAllFK.constraint_name=tblFK.constraint_name

Thnx

September 20, 2008

The media set has 2 media families but only 1 are provided

Filed under: Database, SqlServer — Tags: — patriwala @ 7:28 am

I got this error when restore database from .bak file.

why this error happen?

when you backup the database at that time you have not delete the existing path means you start a back up behalf of the previous one means your backup is divided in to more parts.

steps :
1)  you select all the related .bak file.

example here mydatabase name is test1. first i backup that at that time mybackup name is test1_17.bak. second backup i take at 18 and backup file name is test1_18.bak. now when you selecte restore database at that time you selected both this file.

rightclick on database –> task –> Restore –> Database

open one dialog box — now select fromdevice and add related files (test1_17.bak and test1_18.bak).

* when you take a backup at that time you remove the previous file.

Thnx.

August 18, 2008

Regular Expression in Sqlserver 2005

why Regular Expression Required for sqlserver 2005?

The basic need Of Regular Expression is avoiding hard work for searching or pattern maching in database. Example if i want to search valid email address from users table then what will be senario for that? i have thousand of newly registered user daily. then how to i find invalid Email Address from that?

let’s start with regular expression in sqlserver 2005.

the basic requirement for that configure OLE Object in to Server.

–Configure OLE Automation object.
–EXECUTE permission set for object ’sp_OACreate’
use[master]
GO
GRANT EXECUTE ON[sys].[sp_OASetProperty] TO[public]
GO
use[master]
GO
GRANT EXECUTE ON[sys].[sp_OAMethod] TO[public]
GO
use[master]
GO
GRANT EXECUTE ON[sys].[sp_OAGetErrorInfo] TO[public]
GO
use[master]
GO
GRANT EXECUTE ON[sys].[sp_OADestroy] TO[public]
GO
use[master]
GO
GRANT EXECUTE ON[sys].[sp_OAStop] TO[public]
GO
use[master]
GO
GRANT EXECUTE ON[sys].[sp_OACreate] TO[public]
GO
use[master]
GO
GRANT EXECUTE ON[sys].[sp_OAGetProperty] TO[public]
GO
sp_configure’show advanced options’,1
GO
reconfigure
go

execsp_configure
go
execsp_configure‘Ole Automation Procedures’,1
– Configuration option ‘Ole Automation Procedures’ changed from 0 to 1. Run the RECONFIGURE statement to install.
go
reconfigure
go

steps :

1) Create Scalar Value Function In Sqlserver 2005.

create FUNCTION dbo.RegEx
    (
        --Expression Target / Source
        @Target varchar(5000),
        --Regular Expression Pattern
        @Pattern varchar(Max),
        --whether the expression case sensitive
        @CaseSensitive bit = 0
    )
RETURNS bit
AS
    BEGIN
        DECLARE @ReturnOACreate int
        DECLARE @ObjToken int
        DECLARE @objMatches int
        DECLARE @objMatch int
        DECLARE @count int
        DECLARE @results bit

        EXEC @ReturnOACreate = sp_OACreate 'VBScript.RegExp', @ObjToken OUTPUT

        --objecttoken OUTPUT
        --Is the returned object token, and must be a local variable of data type int.
        --This object token identifies the created OLE object and is used in calls to the other
        --OLE Automation stored procedures.
        --Return
        --0 (success) or a nonzero number (failure) that is the integer value of the
        --HRESULT returned by the OLE Automation object

        IF @ReturnOACreate <> 0 BEGIN
            SET @results = 0
            RETURN @results
        END

        EXEC @ReturnOACreate = sp_OASetProperty @ObjToken, 'Pattern', @Pattern

        IF @ReturnOACreate <> 0 BEGIN
            SET @results = 0
            RETURN @results
        END

        EXEC @ReturnOACreate = sp_OASetProperty @ObjToken, 'Global', false
        IF @ReturnOACreate <> 0 BEGIN
            SET @results = 0
            RETURN @results
        END

        EXEC @ReturnOACreate = sp_OASetProperty @ObjToken, 'IgnoreCase', @CaseSensitive
        IF @ReturnOACreate <> 0 BEGIN
            SET @results = 0
            RETURN @results
        END    

        EXEC @ReturnOACreate = sp_OAMethod @ObjToken, 'Test', @results OUTPUT, @Target
        IF @ReturnOACreate <> 0 BEGIN
            SET @results = 0
            RETURN @results
        END

        EXEC @ReturnOACreate = sp_OADestroy @ObjToken
        IF @ReturnOACreate <> 0 BEGIN
            SET @results = 0
            RETURN @results
        END
    --return 1 for success
    RETURN @results
    END

2) Now use this function for Matching the Expression.

case 1: simple regular expression match

select dbo.RegEx( N'122-45-6789', N'^\d{3}-\d{2}-\d{4}$',0 )
run this it return 0 it indicate this expression is valid.
select dbo.RegEx( N'1224-45-6789', N'^\d{3}-\d{2}-\d{4}$',0 )
run this it return 1 it indicate this expression is InValid.
case 2: Get the data from Table
now the senario is i am finding the valid email address from the table (here i used simple regular expression 
which is made manual for demo purpose you can use any of them.)
 
declare @tblTmp as table(id int identity(1,1),emailaddress varchar(50))

insert into @tblTmp values
('test@yahoo')
insert into  @tblTmp values
('test@gmail.test')
insert into @tblTmp values
('t@gmail.com')
insert into @tblTmp values
('test@test.com')
insert into  @tblTmp values
('test@test.')

select * from @tblTmp

--find valid email address
select * from @tblTmp where
dbo.RegEx(emailaddress,'^[A-Za-z0-9._%-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$',0)=1

 
 
Thnx.
 Reference :

1) MSDN

August 11, 2008

FullText Search In SqlServer 2005

why fulltext search used?

  • Full-text search allows fast and flexible indexing for keyword-based query of text data stored in a SQL Server Database. Unlike the LIKE predicate, which only works on character patterns, full-text queries perform a linguistic search against this data, operating on words and phrases based on rules of a particular language.
  • The performance benefit of using full-text search can be best realized when querying against a large amount of unstructured text data. A LIKE query (for example, ‘%microsoft%’) against millions of rows of text data can take minutes to return; whereas a full-text query (for ‘microsoft’) can take only seconds or less against the same data, depending on the number of rows that are returned.

Keyword Used In FullText Search

   1)FreeText 2)FreeTextTable 3)Contains 4) ContainsTable

 

1)FreeText

  • Is a predicate used to search columns containing character-based data types for values that match the meaning and not the exact wording of the words in the search condition.

2)FreeTextTable

  • Returns a table of zero, one, or more rows for those columns containing character-based data types for values that match the meaning, but not the exact wording, of the text in the specified freetext_string. FREETEXTTABLE can be referenced in the FROM clause of a SELECT statement like a regular table name.

3)Contains

  • A word or phrase.
  • The prefix of a word or phrase.
  • A word near another word.
  • A word inflectionally generated from another (for example, the word drive is the inflectional stem of drives, drove, driving, and driven).
  • A word that is a synonym of another word using thesaurus (for example, the word metal can have synonyms such as aluminum and steel).

4)ContainsTable

  • Returns a table of zero, one, or more rows for those columns containing character-based data types for precise or fuzzy (less precise) matches to single words and phrases, the proximity of words within a certain distance of one another, or weighted matches. CONTAINSTABLE can be referenced in the FROM clause of a SELECT statement as if it were a regular table name.
  • Queries using CONTAINSTABLE specify contains-type full-text queries that return a relevance ranking value (RANK) and full-text key (KEY) for each row. The CONTAINSTABLE function uses the same search conditions as the CONTAINS predicate.

 

I am use the sql server version Standard Edition.

 

Steps:

 

1) Enabled the fulltext on the database using the sp.

   EXEC sp_fulltext_database 'enable'

2) Create Table in Database 

 

CREATE TABLE [dbo].[UserDetail](

[UserDetailId] [int] IDENTITY(1,1) NOT NULL,

[UserId] [int] NULL,

[Address1] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,

[Address2] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,

 CONSTRAINT [PK_UserDetail] PRIMARY KEY CLUSTERED

(

[UserDetailId] ASC

)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

3) Insert Record Into Table

 

INSERT INTO [UserDetail]

([UserId],[Address1],[Address2])

VALUES

(1,’nava india’,'programming’)

INSERT INTO [UserDetail]

([UserId],[Address1],[Address2])

VALUES

(3,’nava america’,'Developing’)

INSERT INTO [UserDetail]

([UserId],[Address1],[Address2])

VALUES

(5,’juna india’,'Testing ‘)

INSERT INTO [UserDetail]

([UserId],[Address1],[Address2])

VALUES

(6,’juna america’,'QA’)

INSERT INTO [UserDetail]

([UserId],[Address1],[Address2])

VALUES

(8,’india’,'PM’)

INSERT INTO [UserDetail]

([UserId],[Address1],[Address2])

VALUES

(3,’japan’,'Developing’)

INSERT INTO [UserDetail]

([UserId],[Address1],[Address2])

VALUES

(3,’nava japan’,'Developing’)

INSERT INTO [UserDetail]

([UserId],[Address1],[Address2])

VALUES

(1,’juna japan’,'programming’)

INSERT INTO [UserDetail]

([UserId],[Address1],[Address2])

VALUES

(1,’america nava’,'programming’)

4) Enabled Full Text in Table

    Right Click On Table

     * Select Full Text Index

       * Define Full Text Index

 

Click Next –> Next

 

 

–here you select Field where you apply full text search field.

select both the field and press Next.

In Next Select automatic and Press Next.

In Next Select Full Text Catalog and Press Next.

Press Next –> Next –> Press Finish Button

 

5) Query Using FullText Search Keyword

5.1) FreeText

  • select * from userdetail where FreeText(Address1,‘nava juna america’)

          Search From Address1 Field where keyword like nava,juna,america.

  • select*fromuserdetail where FreeText(*,‘nava india QA’)

Search From Address1,Address2 Field where keyword like nava,india,QA

5.2 ) FreeTextTable

  • SELECT  * FROM UserDetail AS FT_TBL  INNER JOIN FREETEXTTABLE(UserDetail,Address1,‘nava juna’) AS KEY_TBL

         ON FT_TBL.UserDetailId = KEY_TBL.[KEY];

         –TableName -UserDetail

         –Column Name – Address1

         –Search Keyword -words

Search From Address1 field where keyword like nava juna

  • SELECT * FROM UserDetail AS FT_TBL INNER JOIN FREETEXTTABLE(UserDetail,*, 

    ‘nava PM’) AS KEY_TBL ON FT_TBL.UserDetailId = KEY_TBL.[KEY];

     Search From Address1,Address2 field where keyword like nava,PM

 

5.3)CONTAINS

  • select * from userdetail where Contains(address1,'nava')
search from Address1 where keyword like nava
select * from userdetail where Contains(address1,'nava juna')
you can get the error if you write this with contain keyword.

  • select * from userdetail where Contains(address1,‘”nava” or “india”‘)

          Search From Address1 where keyword like nava or india

 

  • select * from userdetail where Contains(address1,‘”na*”‘)
  • select*fromuserdetail where Contains(*,‘”nava” or “india” or “PM”‘)

         Search From Address1,Address2 where keyword like nava or india or PM

  • select * from userdetail where Contains(*,‘ISABOUT (nava weight (0.8))’)

 

 

Thanks.

 

Reference Site :

MSDN Help

http://msdn.microsoft.com/en-us/library/ms345119.aspx

August 8, 2008

use case in where clause in sqlserver 2005

steps:

–declare temp table
declare@tbl as table(id int,username varchar(50),Age int
)
–insert data into temp table
insert into @tbl
values
(1,‘Amit’,10
) 

insert into @tbl
 

insert into @tbl

values
(1,‘Bhavin’,10
) 

insert into @tbl
 

insert into @tbl

values
(1,‘Chirag’,10
) 

insert into @tbl
 

insert into @tbl

values
(1,‘Dhaval’,10
) 

insert into @tbl
 

insert into @tbl

values
(1,‘Nirav’,10
) 

insert into @tbl
 

insert into @tbl

values
(1,‘kumar’,10
)

–declare variable
declare @username varchar(50
)
set @username =
‘a’ 

select * from @tbl  

select * from @tbl

where
case
@username
     whennullthen1
     when‘a’
then
          case when
username like‘a%’then1 else0
end
     when
‘b’
then
            case when
username like‘b%’then1 else0
end
end
=1

July 23, 2008

Split Function In Sqlserver 2005

Filed under: SqlServer — Tags: — patriwala @ 12:37 pm

1) create below function into database.

-- pass the string 1,2,3
-- delimeter here is ,
Create FUNCTION [dbo].[SplitValue](@Text varchar(Max), @Delimeter varchar(2) = ' ')
RETURNS @ReturnValue TABLE (id int , value varchar(Max))
AS
BEGIN
DECLARE @id int,
    @value varchar(Max),
    @cont bit,
    @strik int,
    @Delimlength int

IF @Delimeter = 'Space'
BEGIN
    SET @Delimeter = ' '
END
--initialize id with 0
SET @id = 0
SET @Text = LTrim(RTrim(@Text))
SET @Delimlength = DATALENGTH(@Delimeter)
SET @cont = 1

IF NOT ((@Delimlength = 0) or (@Delimeter = 'Empty'))
    BEGIN
        WHILE @cont = 1
        BEGIN
        --If you can find the delimiter in the text, retrieve the first element and
        --insert it with its index into the return table.
        IF CHARINDEX(@Delimeter, @Text)>0
            BEGIN
                SET @value = SUBSTRING(@Text,1, CHARINDEX(@Delimeter,@Text)-1)
                BEGIN
                    INSERT @ReturnValue (id, value)
                    VALUES (@id, @value)
                END
                --Increment the index and loop.
                SET @strik = DATALENGTH(@value) + @Delimlength
                SET @id = @id + 1
                SET @Text = LTrim(Right(@Text,DATALENGTH(@Text) - @strik))
            END
        ELSE
        BEGIN
        --If you can’t find the delimiter in the text, @Text is the last value in
        --@ReturnValue.
            SET @value = @Text
            BEGIN
                INSERT @ReturnValue (id, value)
                VALUES (@id, @value)
            END
        --Exit the WHILE loop.
            SET @cont = 0
        END
    END
END
ELSE
BEGIN
    WHILE @cont=1
    BEGIN
    --If the delimiter is an empty string, check for remaining text
    --instead of a delimiter. Insert the first character into the
    --retArray table. Trim the character from the front of the string.
    --Increment the index and loop.
        IF DATALENGTH(@Text)>1
            BEGIN
                SET @value = SUBSTRING(@Text,1,1)
                BEGIN
                INSERT @ReturnValue (id, value)
                VALUES (@id, @value)
                END
                SET @id = @id+1
                SET @Text = SUBSTRING(@Text,2,DATALENGTH(@Text)-1)
            END
        ELSE
            BEGIN
            --One character remains.
            --Insert the character, and exit the WHILE loop.
            INSERT @ReturnValue (id, value)
            VALUES (@id, @Text)
            SET @cont = 0
            END
    END
END
RETURN
END
2) run the following query
select * from dbo.SplitValue('1,2,3',',')
* Here i used reference from othersites.
Thnx.

July 17, 2008

Recursion Function In SqlServer 2005

Create the function which get the total no of child in the parent node.

Steps:

1)      create the table called (tempRecursion)

Fields :

Id int

PId int 

Summary varchar(50) 

Id Pid summary

1   0    a

2   1    b

3   1    c          

4   2    s

     2) now create the function which argument is (id,child count)

FUNCTION [dbo].[fntempRecursion]

(@id int, @getChildInfo int)

bigint

AS

 

BEGIN

 

 

 

 

SET @getChildInfo = @getChildInfo + ( 

 

SELECT Count(id) FROM  tempRecursion WHERE Id =@id )

declare @ref int set @ref =-1 

set @ref =( select pid from tempRecursion where id =@id)

–indicate first node

if(@id <>0 )

( 

SELECT @getChildInfo = dbo.CountChildren(ID, @getChildInfo) FROM

WHERE pid = @id )

END

 

RETURN  @getChildInfo

 

3) run the following query

dbo.fntempRecursion(1,0)

 

Thnx

Older Posts »

Blog at WordPress.com.