Sunday, December 21, 2008

Basic SQL queries

create table Test (Id int Primary Key identity(1, 1), [Name] varchar(50) not null)
alter table Test alter column [Name] int not null
alter table Test add [Age] int not null
delete from Test
DBCC CHECKIDENT (Test, RESEED, 0)
create trigger TestTrigger on Test
FOR INSERT, UPDATE, DELETE
AS
select getDate()
DISABLE TRIGGER ImageTestTrigger ON ImageTest
ENABLE TRIGGER ImageTestTrigger ON ImageTest

drop table Test
DROP trigger TestTrigger

insert into Test([Name], [age]) values('SBala', 25)
update Test Set age = 24 where [Name] = 'SBala'
delete from Test where [Name] = 'SBala'

Create function GetTest() Returns int
as
begin
declare @count int
set @count = (select count(*) from Test)
return @count
end


select dbo.GetTest() as [Count]


begin tran tt
delete from Test
rollback (or) Commit

select * from emp
select e1.[Name], e2.[Name] as Head from emp e1, emp e2
where e1.Head = e2.Id


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER Procedure [dbo].[Emp_Get](@Name varchar(10), @Created varchar(50),
@PhoneNumber int)
as
begin
declare @query varchar(5000)

set @query = 'select * from EMP where '
if(@Name != 'null')
set @query = @query + ' Name = ' + @Name
if(@Created != 'null')
set @query = @query + ' and Created = ' + @Created
if(@PhoneNumber != 0)
set @query = @query + ' and PhoneNumber = ' + cast(@PhoneNumber as varchar(50))
exec(@query)
end



alter Procedure Emp_Get(@Name varchar(10), @Created varchar(50),
@PhoneNumber int)
as
begin
declare @query varchar(5000)

set @query = 'select * from EMP where '
if(@Name != 'null')
set @query = @query + ' Name = ' + @Name
if(@Created != 'null' and @Name != 'null')
set @query = @query + ' and Created = ' + @Created
if(@Created != 'null' and @Name = 'null')
set @query = @query + ' Created = ' + @Created
if(@PhoneNumber != 0)
begin
if(@Created != 'null' or @Name != 'null')
set @query = @query + ' and PhoneNumber = ' + cast(@PhoneNumber as varchar(50))
else
set @query = @query + ' PhoneNumber = ' + cast(@PhoneNumber as varchar(50))
end
exec(@query)
end

No comments: