You are on page 1of 13

Code Snippets - SQL and Connections

Data Binding with Windows Forms 2.0


http://www.ubookcase.com/book/Addison.Wesley/
Data.Binding.with.Windows.Forms.2.0.Programming.Smart.Client.Data.Applications.with.dot.NET/

How to Use OpenRowset to import data from Excel or CSV


without using DTS
SELECT * into temp1 FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel
8.0;Database=C:\RIOFolder\MLA\Esme\Test.xls', Page1$)

or with CSV files

SELECT
* FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Text;Database=C:\Temp\', 'select * from
Book1.csv')

How to Export to Excel using OPENDATASOURCE


insert into OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0', 'Excel
8.0;Database=C:\Temp\Book1.xls')...[Sheet2$]
values(9,'test')

or (to copy from one excel sheet to another)

insert into OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0', 'Excel


8.0;Database=C:\Temp\Book1.xls')...[Sheet2$]
SELECT* FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel
8.0;Database=C:\Temp\Book1.xls', Sheet1$)

How to Import Data to SQL using OpenRowset or BCP


http://blogs.msdn.com/euanga/archive/2006/07/20/672272.aspx

C# for SQL

C# code to retrieve Text of views and Stored Procs


private string GetText(SqlConnection conn, string sTableName)
{
StringBuilder sb = new StringBuilder("");
string sSQL = "select sc.Text from syscomments sc inner join sysobjects so " +
" on sc.id = so.id and so.name = '" + sTableName + "' order by colid";
SqlDataReader dr = clsGenMod.GetDataReader(sSQL, conn);
while (dr.Read())
{
sb.Append(dr["Text"]);
}
dr.Close();
return sb.ToString();
}

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'

To create a global temporary table use ## at the start of the name


select * from dbo.##tmpCoupeTotalPine
This then appears in the sysobjects list from tempdb so to delete it you have to check in
TempDb.dbo.sysobjects for the filename. The help says that it will have a number attached
to it so you may need to use a like % clause but I didn't see that.

How to do a case sensitive search - where clause


delete from Users
where SecurityString like '%H%' COLLATE SQL_Latin1_General_CP1_CS_AS
and username not in
(select name from TIHR.dbo.sysusers)

How to add a sequential number to a result set - note you probably


should use the PK as field to count
SELECT SiteName,
(SELECT COUNT(*) AS Expr1
FROM TechCMDB.dbo.Sites AS s2
WHERE (SiteName <= s1.SiteName)) AS rank
FROM TechCMDB.dbo.Sites AS s1

OR if it is difficult to split them on one field use

update MineralList set ColumnNo =


(select count(*) from MineralList M1
m1.sortOrder < MineralList.SortOrder
where M1.IsCurrent = 1 and
or (m1.sortOrder = MineralList.SortOrder and M1.Mineral
< MineralList.Mineral))

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

How to use Bitwise logical and columns_Updated in trigger


-- =============================================
-- Author: Gerard Hedger
-- Create date: 25/8/07
-- Description: Update trigger to populate the ColumnsUpdated field
-- =============================================
alter
TRIGGER dbo.UpdColsUpdStaff
ON dbo.Staff
AFTER
UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for trigger here
update [dbo].[Staff] set ColumnsUpdated = Columns_Updated(),ColumnsUpdatedString =
tidw.dbo.f_StringAnd(tidw.dbo.f_bin2string(Columns_Updated()),
'0000000000000000000000000000000011111000000000000000000000000000' )
where [StaffRid] in
(select [StaffRid] from Inserted);
END

SQL Functions to do Bitwise logical AND on strings and convert COLUMNS_UPDATED to a


string
-- =============================================
-- Author: Gerard Hedger
-- Create date: 25/8/07
-- Description: Function to 'bitwise' AND but on 2 string representations of binary numbers
-- =============================================
alter
FUNCTION f_StringAnd
(
-- Add the parameters for the function here
@p1
varchar(256),
@Mask
varchar(256)
)
RETURNS
varchar(256)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result varchar(256)
declare @LoopLength as int
declare @LoopPtr as int
set @LoopLength = len(@Mask)
if (len(@p1) < len(@Mask))
set @LoopLength = len(@p1)
-- Add the T-SQL statements to compute the return value here
SELECT @Result = 0
set @LoopPtr = 0
while (@LoopPtr <= @LoopLength )
begin
if (substring(@p1,1,1) = '1' and substring(@Mask,1,1) = '1')
set @Result = @Result + '1'
else
set @Result = @Result + '0'
end
-- Return the result of the function
RETURN @Result
END
GO

SQL function to convert binary representation (e.g. COLUMNS_UPDATED) to a string


-- =============================================
-- Author: Gerard Hedger
-- Create date: 25/8/07
-- Description: Function to turn a binary number into a string representation
-- =============================================
alter
FUNCTION f_bin2string
(
-- Add the parameters for the function here
@p1
varbinary(50)
)
RETURNS
varchar(256)
AS
BEGIN
-- Declare the return variable here
DECLARE @Res varchar(256)
DECLARE @BytePtr int
DECLARE @BitPtr int
set @BytePtr = 1
set @Res = ''
while (@BytePtr <= 8)
begin
set @BitPtr = 1
while (@BitPtr < 256)
begin
set @Res = @Res + coalesce(cast(((cast(substring(@p1,@BytePtr,1) as int) &
@BitPtr)/@BitPtr) as char(1)),'x')
set @BitPtr = @BitPtr * 2
end
set @BytePtr = @BytePtr + 1
end
-- Return the result of the function
RETURN @Res
END
GO

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

How to Connect a Linked server in SQL


EXEC master.dbo.sp_addlinkedserver @server = N'SMS_TOP', @provider=N'SQLNCLI',
@datasrc=N'RIOBRSMS1', @srvproduct=''

How to restore a database from Backup


restore filelistonly from disk='c:\otx\db\tidw.bak'
restore
database TIDW from disk='c:\otx\db\tidw.bak'
with move 'TIDW' to 'c:\otx\db\TIDW.mdf',
move 'TIDW_log' to 'c:\otx\db\TIDW_log.ldf'

How to create a SQL login and grant access to a database


sp_addlogin @loginame='MLALAMS',@passwd='mypwd',@defdb='MLALAMS'
--For some reason it sometimes creates a role with this name which stops the grant access
process from working
sp_droprole 'MLALAMS'
sp_grantdbaccess @loginame='MLALAMS',@name_in_db ='MLALAMS'

sp_addlogin @loginame='MLALAMSITT',@passwd='mypwd',@defdb='MLALAMS'
sp_grantdbaccess @loginame='MLALAMSITT',@name_in_db ='MLALAMSITT'

How to backup and truncate a database and log file


backup log tidw with no_log
backup database tidw to disk='c:\otx\db\TIDWBackup17092007.bak' with COPY_ONLY
dbcc shrinkdatabase('tidw',10)
dbcc shrinkfile('tidw_log',10)
restore filelistonly from disk='c:\otx\db\TIDWBackup17092007.bak'
backup database tidw to disk='c:\otx\db\TIDWBackup170920072.bak'

SQL and Excel


How to update a SQL table from Excel
\\isttw459\c$\Reference\How to Connect to SQL Server and Update from
Excel\UpdateSQL.xls
Connections

ADO Connection Strings - The Code Project - Database


www.codeproject.com/database/connectionstrings.asp
http://www.connectionstrings.com/
http://www.carlprothman.net/Default.aspx?tabid=86#SQLClientManagedProvider
http://www.sqlstrings.com/SQL-Server-connection-strings.htm
http://www.sqlstrings.com/
http://www.connectionstrings.com/ --*******comprehensive list - very good

Example OLEDB connection using Command Timeout


Provider=SQLOLEDB.1;Persist Security Info=False;Integrated
Security=SSPI;CommandTimeout=500;Initial Catalog=" + dbName + ";Data Source=" +
ServerName + ";"

It is possible to set the command timeout in Access adp as follows


http://kbalertz.com/290382/Timeout-Error-Modify-Structure-Large-Table.aspx

SQL Triggers, Stored Procedures, Joins


Check out the HASH join in SQL - I changed a line in sp_userBE and added hash and the
performance was amazing
An example of a hash join which dramatically improved performance - note that the join is
on 2 calculated values
SELECT TOP (1000) A1.CN, A2.CN AS Expr1
FROM
ADUser AS A1 INNER hash JOIN
ADUser
AS A2 ON dbo.f_extract(A1.UserPrincipalName, '.1', 1) =
dbo.f_extract(A2.UserPrincipalName, '@', 1)
WHERE
(A1.UserPrincipalName LIKE '%.1%') AND (A1.BillingEntity IS NULL)
and
(A2.UserPrincipalName not LIKE '%.1%') AND (A2.BillingEntity IS not NULL)

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

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

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

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.


SET NOCOUNT ON;

select * into #tmpIns from Inserted;

exec spTest

-- Insert statements for trigger here

insert into Test select * from #tmpIns

select* from #tmpIns

END

alter PROCEDURE spTest

AS

BEGIN

update #tmpIns set T3 = cast(getdate() as varchar(50))

END

How to Create a Trigger which sets the CreatedOn field


CREATE Trigger [InsStampProject2TaskName] on [dbo].[Project2TaskName]
For Insert
as
update dbo.Project2TaskName
set CreatedOn = getdate(),
CreatedBy = SYSTEM_USER
from Inserted
where Project2TaskName.ProjTaskRid = Inserted.ProjtaskRid

How to assign rid numbers in an INSTEAD OF stored proc


I now have a generic stored proc for this - see below

-- =============================================
-- 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

Database Structure Admin


How to list the SQL for all Views and How to List column names for tables
select * from [dbo].[syscomments]
select * from [dbo].[syscolumns] sc
inner join dbo.sysobjects so
on so.id=sc.id

How to compare 2 databases for changes to table structures


select* from [viewColumns] v1
left outer join
rtsmelsq1.TIDW.dbo.viewcolumns R1 on
R1.Tablename = V1.TableName and R1.ColName = V1.ColName
where R1.tablename is null

orderby 2,1

You might also like