How to avoid writing a subquery?

Filed under: I'm a Newbie, Transact-SQL (T-SQL) — KKline at 6:08 pm on Friday, August 31, 2007

Q:  How to do the query “select * from tbl1 where tbl1.fname like ‘John’ and lname not in (select lname from tbl1 where ybirth>1975 and city=’London’)” without the subquery?

Kevin Kline says:  This is a very simple SQL problem. The following query can be rewritten:

SELECT *
FROM tbl1
WHERE tbl1.fname LIKE ‘John’
AND lname NOT IN (SELECT lname
FROM tbl1
WHERE ybirth>1975 AND city=’London’)

As:

SELECT *
FROM tbl1
WHERE tble1.fname = ‘JOHN’
AND (ybirth <> 1975
AND city <> ‘LONDON’)

Note that you don’t need the LIKE operator since you didn’t use a wildcard operator in the name ‘JOHN’. Also note that ybirth must not be a datetime datatype or else the query would need to say “…AND ybirth <> ‘JAN-01-1975…’ and otherwise follow a proper datetime format.

Technorati Tags:
, ,

How can you view SQL Server through the Internet?

Filed under: Internals and Architecture, Programming, Transact-SQL (T-SQL) — Jason at 4:33 pm on Friday, August 31, 2007

Q:  How can you view SQL Server through the Internet?

Jason Hall says:  Unfortunately, you didn’t tell me if you needed to expose the database to developers, end-users, or administrators. Their needs differ as do the means of exposing SQL Server over the internet to each different type of user.

However, I’ll assume you’re a developer and you want to program an application that is exposed to end-users over the internet. In a situation like this, most people use ASP code.

Read all about it at Microsoft support here.

Technorati Tags:
, ,

How I can handle SQL injection attackcs using a query??

Filed under: Programming, Security, Transact-SQL (T-SQL) — KKline at 3:51 pm on Friday, August 31, 2007

Q:   How I can handle SQL injection in all over application by using query??

Kevin Kline says:   It’s funny that you mention this since Microsoft UK just had a very public SQL Injection attack on their website. It’s reported on TechWorld here.

In essence, a SQL Injection attack is where a programmer has written a web page that exposes a SQL query to the internet. For example, you might write a query that allows the end user of a web page to enter the name of product that they want to find on the web site. However, the web site is now vulnerable to attack because the programmer placed no string checking onto the values returned by the web page, which some malicious person could, instead of putting the name of product into the open field, substitute something like ‘DELETE FROM products’.

SQL Injections is a broad and complex topic though. So you’d best read what the experts have written. I like what NGS Software puts out, such as this white paper.

I also really like Chip Jones’ website called SQL Security.com, which has extensive information on SQL Injection attacks and defenses. It also has a really good utility available for free called LOCKDOWN.SQL.

Technorati Tags:
, , , , , ,

How should I handle very large datafiles?

Filed under: Hardware Considerations, Tuning and Optimization — KKline at 6:46 pm on Thursday, August 30, 2007

Q:  If i have a db of size 500 GB and have only one data file of 350 GB, then: 1) would splitting the data file into multiple files (3) on same File Group would help performance? 2) do all 3 files have to be on the same disk and /or same file group?

Kevin Kline says:  Generally speaking, the main reason you ever segment a database across files and/or filegroups is to put those segments onto separate physical disks. If you don’t place them on separate disk or RAID arrays, then you get no performance improvement because all of the IO still resides in the same place it did before segmentation.

If, on the other hand, you place the filegroups or files onto separate physical disks you will also be moving the IO to separate disks, thus reducing the overall IO load on the disk subsystem(s).

And of course, the first step here is to make sure that the transaction log file is on a separate physical disk or RAID array before doing any of these other steps. If you haven’t done this step first, you’ll still have terrible IO.

Technorati Tags:
, , , , ,

Can we rollback the truncate statment and what is the difference?

Filed under: Transact-SQL (T-SQL) — KKline at 5:59 pm on Thursday, August 30, 2007

Q:  Can we rollback the truncate statment? whats the difference between delete and truncate?

Kevin Kline says:  You cannot rollback TRUNCATE. It is a “non-logged statement”. TRUNCATE removes ALL records from a table.

You -can- rollback DELETE. It is a “logged statement”. DELETE removes one or more records from a table according to the conditions of your WHERE clause.

My recommendation is not to use TRUNCATE in a production application since you cannot recover from it. Instead, use DELETE unless you have a very strong reason to use TRUNCATE.

Technorati Tags:
, , ,

Is the SQL Server 2005 Standard performance twice as fast as SQL Server 2005 Express?

Filed under: Internals and Architecture, Tuning and Optimization — KKline at 5:39 pm on Thursday, August 30, 2007

Q:  Is the SQL Server 2005 Standard performance twice as fast as SQL Server 2005 Express? I sell software that uses both and aside from limitations to the data size and number of users other consultants always say go with Standard it is twice as fast.

Kevin Kline says:  Well, I’d say the other consultants are wrong.

On applications that are agnostic and running relatively few users/connections, you should see little or no difference between Express Edition and Standard Edition.

It is true that Standard Edition can scale much higher. So Standard Edition could potentially be faster (and much more than simply twice as fast) when scaling to dozens, scores, or hundreds of users.

But if the application is for relatively small workloads, the speed should be nearly identical.

Technorati Tags:
, , ,

Does SQL Server make locks at row level?

Filed under: Database Design, I'm a Newbie, SQL Server 2005 — SQL Stan at 4:51 pm on Tuesday, August 28, 2007

Q:  Is it true that SQL Server 2005 doesn’t make locks at row level and only makes page-level locks?

Iain Kick says:   No, SQL Server can create locks at the row level and escalate to page, extent, table and database level as neccessary. More details on SQL Server locking can be found at sql-server-performance.com.

Technorati Tags:
, , , ,

What is the difference between GROUP BY and HAVING clauses?

Filed under: I'm a Newbie, Programming, Transact-SQL (T-SQL) — Bryan Oliver at 4:32 pm on Tuesday, August 28, 2007

Q:  What is the difference between GROUP BY and HAVING clauses?

Bryan Oliver says:  The GROUP BY and HAVING clauses are used together. The HAVING clause is used as a final filter (rather than as a conditional filter) on the aggregate column values in the result set of a SELECT statement. In other words, the query has to be grouped before the HAVING clause can be applied. For example, consider the following statement, which displays the count of students in various classes (classes of students = 1, 2, 3, 4, corresponding to freshman, sophomore, and so on). For an excellent overview of these clauses, check out the online reference at w3schools.com.

Technorati Tags:
, , , ,

How do I update two tables in different databases?

Filed under: Database Design, Programming, Transact-SQL (T-SQL), Tuning and Optimization — Bryan Oliver at 4:22 pm on Tuesday, August 28, 2007

Q:  I am trying to build a trigger that updates a similar table on another database. It seems to work OK if I define all fields to be updated in the UPDATE statement. If I try to construct the statement using a cursor to read the fields and then exec it, the table is not recognized. How can I solve this?

Bryan Oliver says:  Try the following block of code for updating two tables

/*
This trigger audit trails all changes made to a table.
It will place in the table Audit all inserted, deleted, changed columns in the table on which it is placed.
It will put out an error message if there is no primary key on the table
You will need to change @TableName to match the table to be audit trailed
*/

–Set up the tables
if exists (select * from sysobjects where id = object_id(N’[dbo].[Audit]‘) and OBJECTPROPERTY(id, N’IsUserTable’) = 1)
drop table [dbo].[Audit]
go
create table Audit (Type char(1), TableName varchar(128), PK varchar(1000), FieldName varchar(128), OldValue varchar(1000), NewValue varchar(1000), UpdateDate datetime, UserName varchar(128))
go
if exists (select * from sysobjects where id = object_id(N’[dbo].[trigtest]‘) and OBJECTPROPERTY(id, N’IsUserTable’) = 1)
drop table [dbo].[trigtest]
go
create table trigtest (i int not null, j int not null, s varchar(10), t varchar(10))
go
alter table trigtest add constraint pk primary key (i, j)
go

create trigger tr_trigtest on trigtest for insert, update, delete
as

declare @bit int ,
@field int ,
@maxfield int ,
@char int ,
@fieldname varchar(128) ,
@TableName varchar(128) ,
@PKCols varchar(1000) ,
@sql varchar(2000),
@UpdateDate varchar(21) ,
@UserName varchar(128) ,
@Type char(1) ,
@PKSelect varchar(1000)

select @TableName = ‘trigtest’

– date and user
select @UserName = system_user ,
@UpdateDate = convert(varchar(8), getdate(), 112) + ‘ ‘ + convert(varchar(12), getdate(), 114)

– Action
if exists (select * from inserted)
if exists (select * from deleted)
select @Type = ‘U’
else
select @Type = ‘I’
else
select @Type = ‘D’

– get list of columns
select * into #ins from inserted
select * into #del from deleted

– Get primary key columns for full outer join
select @PKCols = coalesce(@PKCols + ‘ and’, ‘ on’) + ‘ i.’ + c.COLUMN_NAME + ‘ = d.’ + c.COLUMN_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
where pk.TABLE_NAME = @TableName
and CONSTRAINT_TYPE = ‘PRIMARY KEY’
and c.TABLE_NAME = pk.TABLE_NAME
and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

– Get primary key select for insert
select @PKSelect = coalesce(@PKSelect+’+',”) + ”’<’ + COLUMN_NAME + ‘=”+convert(varchar(100),coalesce(i.’ + COLUMN_NAME +’,d.’ + COLUMN_NAME + ‘))+”>”’
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
where pk.TABLE_NAME = @TableName
and CONSTRAINT_TYPE = ‘PRIMARY KEY’
and c.TABLE_NAME = pk.TABLE_NAME
and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

if @PKCols is null
begin
raiserror(’no PK on table %s’, 16, -1, @TableName)
return
end

select @field = 0, @maxfield = max(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName
while @field < @maxfield
begin
select @field = min(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName and ORDINAL_POSITION > @field
select @bit = (@field - 1 )% 8 + 1
select @bit = power(2,@bit - 1)
select @char = ((@field - 1) / 8) + 1
if substring(COLUMNS_UPDATED(),@char, 1) & @bit > 0 or @Type in (’I',’D')
begin
select @fieldname = COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName and ORDINAL_POSITION = @field
select @sql = ‘insert Audit (Type, TableName, PK, FieldName, OldValue, NewValue, UpdateDate, UserName)’
select @sql = @sql + ‘ select ”’ + @Type + ””
select @sql = @sql + ‘,”’ + @TableName + ””
select @sql = @sql + ‘,’ + @PKSelect
select @sql = @sql + ‘,”’ + @fieldname + ””
select @sql = @sql + ‘,convert(varchar(1000),d.’ + @fieldname + ‘)’
select @sql = @sql + ‘,convert(varchar(1000),i.’ + @fieldname + ‘)’
select @sql = @sql + ‘,”’ + @UpdateDate + ””
select @sql = @sql + ‘,”’ + @UserName + ””
select @sql = @sql + ‘ from #ins i full outer join #del d’
select @sql = @sql + @PKCols
select @sql = @sql + ‘ where i.’ + @fieldname + ‘ <> d.’ + @fieldname
select @sql = @sql + ‘ or (i.’ + @fieldname + ‘ is null and d.’ + @fieldname + ‘ is not null)’
select @sql = @sql + ‘ or (i.’ + @fieldname + ‘ is not null and d.’ + @fieldname + ‘ is null)’
exec (@sql)
end
end
go

insert trigtest select 1,1,’hi’, ‘bye’
insert trigtest select 2,2,’hi’, ‘bye’
insert trigtest select 3,3,’hi’, ‘bye’
select * from Audit
select * from trigtest
update trigtest set s = ‘hibye’ where i <> 1
update trigtest set s = ‘bye’ where i = 1
update trigtest set s = ‘bye’ where i = 1
update trigtest set t = ‘hi’ where i = 1
select * from Audit
select * from trigtest
delete trigtest
select * from Audit
select * from trigtest

go
drop table Audit
go
drop table trigtest
go

Technorati Tags:
, , , , ,

Is there any easy way of restoring a SQL Server 2005 backup file to a SQL Server 2000 instance? I have customers that need to restore databases but do not have SQL 2005 installed.

Filed under: Backup and Restore, SQL Server 2005 — Jason at 8:49 am on Friday, August 24, 2007

Jason Hall says:  You cannot restore a SQL Server 2005 backup file to a SQL 2000 instance as the SQL 2000 restore engine does not recognize the SQL 2005 format.  Your customers do have a few options though.  Assuming that the database is less than two gigs in size you can install a copy of SQL Server 2005 Express Edition, which is free to use, and restore to this system.  Another option is for you to restore the backup file to a SQL Server 2005 instance and run the Copy Database Utility inside of SQL Server Management Studio to copy the database to a SQL Server 2000 instance.  You could then re-backup the database and ship them the new ”downgraded” database. 

 If anyone else has any suggestions please let us know. 

Next Page »