Professional Documents
Culture Documents
SELECT
* FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Text;Database=C:\Temp\', 'select * from
Book1.csv')
C# for SQL
SQL
How to write DELETE and UPDATE statements based on an alias
delete from T1 from Temp1 T1
inner join Temp1 T2 on T1.mineral= t2.mineral
where t1.mineral = 'x'
update T1
set mineral = 'y'
from Temp1 T1 inner join Temp1 T2 on T1.mineral = t2.mineral
where t1.mineral = 'x'
SQL View which gets SMS scans for servers and workstations
select distinct DateDiff(d,Sub1.LastHWScan,getdate()) as DaysSinceHWScan,*
from tmpCompBE inner join
(select sys.Netbios_Name0,
IsNULL(disc.AgentTime,Var1.NullVal) AgentTime,
IsNULL(hw.LastHWScan,Var1.NullVal) as LastHWScan,
IsNULL(sw.LastScanDate,Var1.NullVal) as LastSWScan
from
(select NullVal=CONVERT(datetime,'1/1/2006')) as Var1,
(select LastDate=DATEADD(dd,-convert(int,Var3.NumOfDays),GetDate())
from (select NumOfDays=0) as Var3) as Var2,
SMS_TOP.SMS_TOP.dbo.v_R_System sys
left join
(
select ResourceId, MAX(AgentTime) as AgentTime
from SMS_TOP.SMS_TOP.dbo.v_AgentDiscoveries
group by ResourceId
) as disc on disc.ResourceId = sys.ResourceID
left join SMS_TOP.SMS_TOP.dbo.v_GS_WORKSTATION_STATUS hw on hw.ResourceID =
sys.ResourceID
left join SMS_TOP.SMS_TOP.dbo.v_GS_LastSoftwareScan sw on sw.ResourceID =
sys.ResourceID
where (IsNULL(disc.AgentTime,Var1.NullVal) < Var2.LastDate
or IsNULL(hw.LastHWScan,Var1.NullVal) < Var2.LastDate
or IsNULL(sw.LastScanDate,Var1.NullVal) < Var2.LastDate)
and sys.Client0 = 1
) as Sub1
on tmpCompBE.servername = Sub1.Netbios_Name0
order by 1 desc
How to Convert SQL dateTime to Date Only - particularly useful for comparing 2
dates which have time values which need to be ignored
CREATE FUNCTION [dbo].[DateTime2Date] (@inDateTime as Datetime)
RETURNS Datetime AS
BEGIN
return CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, @inDateTime)))
END
Consider using sp_executesql to run dynamic SQL - allows input and output
parameters
see http://www.mssqlserver.com/faq/development-dynamicsql.asp
SQL Admin - Backup, Restore, Login
To see the last SQL statement run on a SPID use
DBCC inputbuffer(spidno)
Under Management there is an activity monitor as well
sp_addlogin @loginame='MLALAMSITT',@passwd='mypwd',@defdb='MLALAMS'
sp_grantdbaccess @loginame='MLALAMSITT',@name_in_db ='MLALAMSITT'
How to see the text of every View, Trigger, Stored Proc and
Constraint in the database
select O1.Name,S1.text from syscomments S1 left outer join sysobjects O1 on O1.id = s1.id
How to call a stored proc from a trigger to update the rid value
-- =============================================
-- Author: Gerard Hedger
-- Create date: 21/10/07
-- Description: Insert trigger for Batch
-- =============================================
ALTERTRIGGER [dbo].[InsBatch] ON [dbo].[Batch]
INSTEAD OF INSERT
AS
exec sp_UpdateBatch
where CreatedBy is null -- this is added so that a user can be set by the client program
-- =============================================
-- Author: Gerard Hedger
-- Create date: 21/10/07
-- Description: Generic Procedure called by the insert triggers
-- =============================================
ALTER PROCEDURE [dbo].[sp_UpdateRid]
@TableName as varchar(50),
@LastRid as int,
AS
BEGIN
set @More = 1;
begin
set @SQLString = N'update top (1) ' + cast(@TableName as nvarchar(50)) + ' set ' +
@RidFieldName + ' = ' + cast(@NextRec as nvarchar(10)) + ' where Rid is null'
if @@rowcount = 0
set @More = 0
end
END
A temp table created in a trigger is available to a stored procedure that is called from the
trigger (probably not limited to that)
This means it is possible to write a stored proc that can be used by both the insert and the
update statement to ensure consistency.
Also, a trigger can return a recordset (select * from #tmpIns) so an insert statement or
update can display the results of the operation (not sure if this is useful)
alter TRIGGER [dbo].[InsTest] ON [dbo].[Test]
INSTEAD OF INSERT
AS
BEGIN
exec spTest
END
AS
BEGIN
END
-- =============================================
-- Author: Gerard Hedger
-- Create date: 21/10/07
-- Description: Insert trigger for Batch
-- =============================================
ALTER
TRIGGER [dbo].[InsBatch] ON [dbo].[Batch]
INSTEAD
OF INSERT
AS
select
* into #tmpInsBatch from Inserted;
Declare
@LastRid as int
set
@LastRid = isnull((select max(Rid) from [Batch]),0)
exec
sp_UpdateRid '#tmpInsBatch',@LastRid
exec
sp_UpdateBatch
update
#tmpInsBatch set CreatedOn = getdate(),CreatedBy = system_user
where
CreatedBy is null -- this is added so that a user can be set by the client program
insert
into Batch
select
* from #tmpInsBatch
-- =============================================
-- Author: Gerard Hedger
-- Create date: 21/10/07
-- Description: Generic Procedure called by the insert triggers
-- =============================================
ALTER
PROCEDURE [dbo].[sp_UpdateRid]
-- Add the parameters for the stored procedure here
@TableName
as varchar(50),
@LastRid
as int,
@RidFieldName
as varchar(50) = 'Rid'
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @NextRec as int;
declare @More as int;
DECLARE @SQLString nvarchar(500);
--Assign rid numbers
set @NextRec = @LastRid+1
--Have any records got a null in the rid field
set @More = 1;
while (@More > 0)
begin
--Update 1 record at a time
set @SQLString = N'update top (1) ' + cast(@TableName as nvarchar(50)) + ' set ' +
@RidFieldName + ' = ' + cast(@NextRec as nvarchar(10)) + ' where Rid is null'
exec sp_executesql @SQLString
if @@rowcount = 0
set @More = 0
set @NextRec = @NextRec + 1
end
END
Use an Instead of trigger for Insert and Updates
good example in TIHR table Staff
-- =============================================
-- Author: Gerard Hedger
-- Create date: 28/8/07
-- Description: Trigger to insert new records into Staff
-- =============================================
ALTER
TRIGGER [dbo].[InsStaff]
ON [dbo].[Staff]
instead of INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--Raiserror('Testc',1,-1)
--insert into staff (staffrid,versionno,staffno) values (5,5,5)
Declare @Reccnt as int
Declare @NextRec as int
Declare @Msg as varchar(150)
--set @Msg = '3test' +cast(@Reccnt as varchar(50))
--Raiserror(@Msg,16,1)
select * into #tmpStaff from inserted --where staffrid is null
update #tmpStaff set VersionNo = 0 where VersionNo is null
update #tmpStaff set ServerLastUpdatedOn = getdate() , CreatedOn = getdate(),
CreatedBy = user_name()
select @Reccnt = count(*) from #tmpStaff
set @NextRec = isnull((select max(staffrid) from staff),0) + 1
if @Nextrec is null
set @Nextrec = 1
--set @Msg = '4test' +cast(@Reccnt as varchar(50))
--Raiserror(@Msg,16,1)
if (@Reccnt > 1)
begin
Declare @StaffRid as int
Declare Staff_curs Cursor for
select staffRid from #tmpStaff
open Staff_curs
fetch next from Staff_curs into @Staffrid
while @@FETCH_STATUS = 0
begin
--set @Msg = '5test' +cast(@NextRec as varchar(50))
--Raiserror(@Msg,16,1)
UPDATE #tmpStaff
SET StaffRid = @NextRec
WHERE CURRENT OF Staff_curs;
set @NextRec = @NextRec + 1
fetch next from Staff_curs into @Staffrid
end
Close Staff_curs;
Deallocate Staff_curs;
end
else
begin
update #tmpStaff set StaffRid = @NextRec
end
insert into Staff select * from #tmpStaff
insert into StaffArchive
select * from #tmpStaff
where not exists
(select 1 from Staffarchive
where Staffarchive.StaffRid = #tmpStaff.StaffRid and Staffarchive.VersionNo =
#tmpStaff.VersionNo)
END
How to Set the Rid value on one record at a time - this is used in the
stored procedure sp_UpdateRid
This method is required for SQL 2000 because 2005 has the ability to do 'update top (1) set
...'
update T1 set RawLLAMAHeadingRid = 3240
from #tmpRawLLAMAHeading as T1 inner join
(select top 1 * from #tmpRawLLAMAHeading where RawLLAMAHeadingRid is null and
ColumnHeading is not null order by ColumnHeading) as T2
on T1.ColumnHeading = T2.ColumnHeading
where T1.RawLLAMAHeadingRid is null
orderby 2,1