Showing posts with label book. Show all posts
Showing posts with label book. Show all posts

Monday, March 19, 2012

2q - Indexs and Optimize...

Mikael:
When people ask me this question (#1), I always say, look at the phone
book. You can think of a phone book as being like a 2-way composite
index on Lastname (Ascending) and Firstname (Ascending), in that order:
Adams, John
Bryant, Frank
Coolidge, Adam
Coolidge, Calvin
Coolidge, Zach
If you ordered it as Lastname (Ascending) and Firstname (Descending):
Adams, John
Bryant, Frank
Coolidge, Zach
Coolidge, Calvin
Coolidge, Adam
If you ordered it as First name (Ascending) ...
Coolidge, Adam
Coolidge, Calvin
Bryant, Frank
Adams, John
Coolidge, Zach
Get the idea?
MC wrote:
> As far as 1) goes theres a world of difference. I would suggest reading
> about indexes, if you have the time 'Inside Sql server 2000' would probably
> give you all the answers you need.
> 2) you can use Profiler tool. Trace queries and possibly filter them by
> duration value. If you put over 3000 you'll see only queries that last over
> 3 seconds...
>
> MC
> "Mikael Syska" <news01@.syska.dk> wrote in message
> news:OBZvoioXHHA.1388@.TK2MSFTNGP05.phx.gbl...
>
"Mikael Syska" <news01@.syska.dk> wrote in message
news:eS7AKXsXHHA.3952@.TK2MSFTNGP04.phx.gbl...
> Yes, I think so ...
> So an index on FirstName DESC, LastName ASC
> and the query ...
> SELECT Firname, LastName FROM t1 ORDER BY LastName, FirstName
> would are the list after that index ... ASC on FirstName and DESC on
> LastName ?
No, ASC on both. An ORDER BY is ASCending unless otherwise specified.
However, the query plans will be different.
Given this script:
create table order_test
( fname varchar(10),
lname varchar(10))
insert into order_test values ('albert', 'zilch')
insert into order_test values ('albert', 'allen')
insert into order_test values ('albert', 'Brend')
insert into order_test values ('Bill', 'zilch')
insert into order_test values ('Bill', 'Cramden')
insert into order_test values ('Wendy', 'Jillson')
create index fname_idx on order_test (fname asc, lname desc)
go
set showplan_all on
go
select * from order_test order by fname, lname
select * from order_test order by fname, lname desc
drop table order_test

Since we're ordering the results in "reverse" of the index, we have an extra
scan in there.
creating an INDEX with DESC is useful when you will generally return the
results in DESC order. It's just an optimization step.
select * from order_test order by fname, lname
|--Sort(ORDER BY[testing].[dbo].[order_test].[fname] ASC,
[testing].[dbo].[order_test].[lname] ASC))
|--Index Scan(OBJECT[testing].[dbo].[order_test].[fname_idx]))
select * from order_test order by fname, lname desc
|--Index Scan(OBJECT[testing].[dbo].[order_test].[fname_idx]), ORDERED
FORWARD)
[vbcol=seagreen]
> and if I had a other index on FirstName ASC and did a
> SELECT Firname, LastName FROM t1 ORDER BY FirstName
> it would sort DESC ... right ? if i guess they are grouped ...
> But are there any performance gain by doing it that way (then some columns
> would be added more than 1 time) ?
> best regrads
> Mikael Syska
> David Markle wrote:
Greg Moore
SQL Server DBA Consulting
sql (at) greenms.com http://www.greenms.com

Sunday, March 11, 2012

2-nd edition of Celko Puzzle book in the works

2-nd edition of Celko Puzzle book in the works
I am getting material for a second edition of my SQL PUZZLES book
together of the next few months.
1) If anyone has a new puzzle, send it to me. You will get your name
in print, fame, glory and perhaps a free copy, depending on my
publisher.
2) If anyone has a new answer to an old puzzle, send it to me. In
particular, when I wrote the first edition, most products were still
using the SQL-86 Standards. That meant no OUTER JOIN, no CTE, no
derived tables, and limited standardized functions and so forth.
I'd like to see new answers with SQL-92 stuff and SQL-99 OLAP
extensions.
3) I will post some of the oldies on newsgroups and fish for new
answers. I will reward the best ones with an old IT book from my
library. I will try to keep my choice in the database area, but you
could get a copy of something weird, like an illustrated history of
punch cards.
4) Here is a starter, an oldie that appeared in one of my magazine
columns over a decade ago, before we had standard OUTER JOIN syntax.
My original answer was a complex nested nightmare; can you do better?
You are given an abbreviated table of personnel salary history
CREATE TABLE Salaries
(emp_name CHAR(10) NOT NULL,
sal_date DATETIME NOT NULL,
sal_amt DECIMAL (8,2) NOT NULL,
PRIMARY KEY (emp_name, sal_date));
INSERT INTO Salaries VALUES ('Tom', '1996-06-20', 500.00);
INSERT INTO Salaries VALUES ('Tom', '1996-08-20', 700.00);
INSERT INTO Salaries VALUES ('Tom', '1996-10-20', 800.00);
INSERT INTO Salaries VALUES ('Tom', '1996-12-20', 900.00);
INSERT INTO Salaries VALUES ('Dick', '1996-06-20', 500.00);
INSERT INTO Salaries VALUES ('Harry', '1996-07-20', 500.00);
INSERT INTO Salaries VALUES ('Harry', '1996-09-20', 700.00);
The goal is to produce a query that will show us the current salary and
the effective date of each employee, and his immediately previous
salary and effective date. If he is a new employee, then his previous
salary and effective date are shown as NULL. The results of the sample
data are:
Result
emp_name curr_date curr_amt prev_date prev_amt
========================================
==========
'Tom' '1996-12-20' 900.00 '1996-10-20' 800.00
'Harry' '1996-09-20' 700.00 '1996-07-20' 500.00
'Dick' '1996-06-20' 500.00 NULL NULLA new answer to an oldie?
WITH SalariesRank(emp_name,sal_date,sal_amt,P
os) AS
(SELECT emp_name,
sal_date,
sal_amt,
RANK() OVER(PARTITION BY emp_name ORDER BY sal_date DESC)
FROM Salaries)
SELECT c.emp_name,
c.sal_date AS curr_date,
c.sal_amt AS curr_amt,
p.sal_date AS prev_date,
p.sal_amt AS prev_amt
FROM SalariesRank c
LEFT OUTER JOIN SalariesRank p ON p.emp_name=c.emp_name AND p.Pos=2
WHERE c.Pos=1|||I like it!! here is the version I came up with, but have not tested:
SELECT S1.emp_name,
MAX (CASE WHEN rn = 1 THEN sal_date ELSE NULL END) AS curr_date,
MAX (CASE WHEN rn = 1 THEN sal_amt ELSE NULL END) AS curr_amt,
MAX (CASE WHEN rn = 2 THEN sal_date ELSE NULL END) AS prev_date,
MAX (CASE WHEN rn = 2 THEN sal_amt ELSE NULL END) AS prev_amt,
FROM (SELECT emp_name, sal_date, sal_amt,
RANK()OVER (PARTITION BY S1.emp_name ORDER BY sal_date
DESC)
FROM Salaries) AS S1 (emp_name, sal_date, sal_amt, rn)
WHERE rn < 3
GROUP BY S1.emp_name;
I avoid an OUTER JOIN, but at the expense of a GROUP BY.
Anybody else got one?|||Sorry, my format is no good, but this one is outer join wth correlated subs.
.
SELECT CS.Emp_name,
CS.Sal_date AS Curr_date,
CS.Sal_amt AS Curr_amt,
PS.Sal_date AS Prev_date,
PS.Sal_amt AS Prev_amt
FROM #Salaries CS LEFT OUTER JOIN
(SELECT Emp_name, Sal_date, Sal_amt FROM #Salaries t1
WHERE t1.Sal_Date = (SELECT MAX(Sal_date)
FROM #Salaries s2
WHERE s2.Emp_name = t1.Emp_name
AND s2.Sal_date < (SELECT MAX(Sal_date)
FROM #Salaries s3
WHERE s3.Emp_name = S2.Emp_name))) PS
ON CS.Emp_name = PS.Emp_name
WHERE CS.Sal_date = (SELECT MAX(Sal_date)
FROM #Salaries s1
WHERE s1.Emp_name = CS.Emp_name)|||> f anyone has a new answer to an old puzzle, send it to me
Joe,
what's the e-mail?|||jcelko212@.earthlink.net
I have the highest possible firewall, so I will need to let you in.|||How about a simple:
SELECT S1.emp_Name, S1.sal_date, S1.sal_amt, S2.Sal_date, S2.Sal_amt,
S3.sal_date
FROM Salaries S1
LEFT JOIN Salaries S2 ON S1.Emp_name = S2.Emp_name AND
S1.Sal_date > S2.Sal_date
LEFT JOIN Salaries S3 ON S1.Emp_name = S3.Emp_name AND
(S3.Sal_date > S1.Sal_date OR (S3.Sal_date > S2.Sal_date
AND S3.Sal_date < S1.Sal_date ))
WHERE S3.Emp_name IS NULL|||this is my attempt to solve the puzzle:
SELECT S1.emp AS emp_name, S1.sal_date AS curr_date, S1.sal_amt AS curr_amt,
CASE WHEN S2.sal_date <> S1.sal_date THEN S2.sal_date END AS prev_date,
CASE WHEN S2.sal_date <> S1.sal_date THEN S2.sal_amt END AS prev_amt
FROM Salaries AS S1
INNER JOIN Salaries AS S2
ON S2.emp = S1.emp
AND S2.sal_date = COALESCE((SELECT MAX(S4.sal_date)
FROM Salaries AS S4
WHERE S4.emp = S1.emp
AND S4.sal_date < S1.sal_date), S2.sal_date)
WHERE NOT EXISTS(SELECT *
FROM Salaries AS S3
WHERE S3.emp = S1.emp
AND S3.sal_date > S1.sal_date);
Andrey Odegov
avodeGOV@.yandex.ru
(remove GOV to respond)

Tuesday, March 6, 2012

2005: using SMO

Hello,
I am learning SQL Server 2005. I would like to write a procedure
making database backup using SMO. According to my book I should write
such code:

using Microsoft.SqlServer.Management.SMO;
public static void MakeBackup()
{
Server server = new Server("localhost");
Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.BackupSetName = "Backup copy";
backup.BackupSetDescription = "Backup copy";
backup.Database = "DemoSQLServer";
backup.Devices.AddDevice("C:\\DemoSQLServer.bak",
DeviceType.File);
backup.SqlBackup(server);
}

The code cannot be compiled because of error:
The type or namespace name 'Management' does not exist in the
namespace 'Microsoft.SqlServer'.
Please help to correct the problem - I cannot find proper name of SMO
namespace. Is the code OK?
Thank you very much
/RAM/I tried adding references to Microsoft.SqlServer.ConnectionInfo and
Microsoft.SqlServer.Smo - and I could build assembly. But then I
cannot create assembly in SQL Server:

"An exception occured while executing a Transact statement or batch
(Microsoft.SqlServer.Express.ConnectionInfo).
Assembly 'microsoft.sqlserver.smo, version=9.0.242.0, culture=neutral,
publictoken=89845dcd8080cc91.' was not found in the SQL catalog.
(Microsoft SQL Server, Error: 6503)"

Could you help me to solve it...|||R.A.M. (r_ahimsa_m@.poczta.onet.pl) writes:

Quote:

Originally Posted by

I tried adding references to Microsoft.SqlServer.ConnectionInfo and
Microsoft.SqlServer.Smo - and I could build assembly. But then I
cannot create assembly in SQL Server:
>
"An exception occured while executing a Transact statement or batch
(Microsoft.SqlServer.Express.ConnectionInfo).
Assembly 'microsoft.sqlserver.smo, version=9.0.242.0, culture=neutral,
publictoken=89845dcd8080cc91.' was not found in the SQL catalog.
(Microsoft SQL Server, Error: 6503)"
>
Could you help me to solve it...


There is a smaller set of .Net Fx assemblies that are loaded by default
in SQL Server. Apparently Microsoft.SqlServer.Smo is not one of them.
You could create an assembly in your database for the DLL with CREATE
ASSEMBLY, but I suspect that there is a reason why this DLL is not
loaded. I don't think the intention is that SMO is to be called from
within SQL Server. (But I have stayed away from SMO, so I don't really
know for sure.)

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

2005: Business Intelligence Development Studio?

Hello,
I am learning SQLServer 2005 Express Edition. I wanted to learn Report
Designer which - according to my tutorial book - is part of Business
Intelligence Development Studio. I can't find it in Internet. Could
you help me plase?
Thank you very much!
/RAM/It only comes with Express Advanced Services and not Express, they are both
free.

--
Tony Rogerson
SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
Server Consultant
http://sqlserverfaq.com - free video tutorials

"R.A.M." <r_ahimsa_m@.poczta.onet.plwrote in message
news:p2f6b2d20jnmn9mfdvsh8504p5d4aml0s0@.4ax.com...

Quote:

Originally Posted by

Hello,
I am learning SQLServer 2005 Express Edition. I wanted to learn Report
Designer which - according to my tutorial book - is part of Business
Intelligence Development Studio. I can't find it in Internet. Could
you help me plase?
Thank you very much!
/RAM/
>

|||On Tue, 11 Jul 2006 07:11:36 +0100, "Tony Rogerson"
<tonyrogerson@.sqlserverfaq.comwrote:

Quote:

Originally Posted by

>It only comes with Express Advanced Services and not Express, they are both
>free.


I have just installed Express Edition Advanced Services. I see no
Business Intelligence application. What should I do?
Please help.
/RAM/|||I have installed also SQLEXPR_TOOLKIT.EXE. Now I see "SQL Server
Business Intelligence Development Studio" in the Start menu with a
link to "C:\Program Files\Microsoft Visual Studio
8\Common7\IDE\devenv.exe" - but I do not have such file. What should I
do? Please help
/RAM/

2005: BACKUP

Hello,
I am learning SQL Server 2005. I need to know how to make a backup of
a database. I tried (according to my book):
BACKUP DATABASE DemoSQLServer TO DISK = "G:\DemoSQLServer.bak"
But I got error:
Incorrect syntax near 'G:\DemoSQLServer.bak'.
Please help.
Thank you very much.
/RAM/RAM (r_ahimsa_m@.poczta.onet.pl) writes:

Quote:

Originally Posted by

I am learning SQL Server 2005. I need to know how to make a backup of
a database. I tried (according to my book):
BACKUP DATABASE DemoSQLServer TO DISK = "G:\DemoSQLServer.bak"
But I got error:
Incorrect syntax near 'G:\DemoSQLServer.bak'.
Please help.


If the book fails, try Books Online.

Generally, in T-SQL, single quote is used as the string delimiter. (Although
it is possible with a legacy setting in force also use double quote as
string delimiter, but this is not recommended.)

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||The error is the double quotes! You need to use single quotes to
specify the filename. The statement should be rewritten as:
BACKUP DATABASE DemoSQLServer TO DISK = 'G:\DemoSQLServer.bak'

N.I.T.I.N.

RAM wrote:

Quote:

Originally Posted by

Hello,
I am learning SQL Server 2005. I need to know how to make a backup of
a database. I tried (according to my book):
BACKUP DATABASE DemoSQLServer TO DISK = "G:\DemoSQLServer.bak"
But I got error:
Incorrect syntax near 'G:\DemoSQLServer.bak'.
Please help.
Thank you very much.
/RAM/

|||On 25 Jul 2006 00:24:24 -0700, "NiTiN" <emailme.nitin@.gmail.com>
wrote:

Quote:

Originally Posted by

>The error is the double quotes! You need to use single quotes to
>specify the filename. The statement should be rewritten as:
>BACKUP DATABASE DemoSQLServer TO DISK = 'G:\DemoSQLServer.bak'


Thanks,
but I have another problem:
Cannot open backup device 'G:\DemoSQLServer.bak'. Operating system
error 5(Access denied.).

(Changing drive don't help.)
I have no problem with accessing drives from other applications. I had
no problems with SQL Server setup.

Please help.
/RAM/|||"RAM" <r_ahimsa_m@.poczta.onet.plwrote in message
news:6lkec292thjpbhkm7b2h03unpeg045jhp2@.4ax.com...

Quote:

Originally Posted by

On 25 Jul 2006 00:24:24 -0700, "NiTiN" <emailme.nitin@.gmail.com>
wrote:
>

Quote:

Originally Posted by

The error is the double quotes! You need to use single quotes to
specify the filename. The statement should be rewritten as:
BACKUP DATABASE DemoSQLServer TO DISK = 'G:\DemoSQLServer.bak'


>
Thanks,
but I have another problem:
Cannot open backup device 'G:\DemoSQLServer.bak'. Operating system
error 5(Access denied.).
>
(Changing drive don't help.)
I have no problem with accessing drives from other applications. I had
no problems with SQL Server setup.


SQL Server itself for some reason doesn't have access to this drive.

If it's local, check permissions.

If it's remote, change it to a UNC path and make sure the user has domain
priviliges.

Quote:

Originally Posted by

>
Please help.
/RAM/
>

|||but I have another problem:

Quote:

Originally Posted by

Cannot open backup device 'G:\DemoSQLServer.bak'. Operating system
error 5(Access denied.).
>
(Changing drive don't help.)


Hi!

My guess is that you need to grant filesystem privileges to the account
that SQL Server runs as. That account is usually sysopr.

N.I.T.I.N.|||>My guess is that you need to grant filesystem privileges to the account

Quote:

Originally Posted by

>that SQL Server runs as. That account is usually sysopr.


I have little experience with Microsoft software...
On my Windows XP computer I have two accounts Robert (admin) and
Guest. I have installed SQL Server 2005 on Robert's account. I haven't
found information about sysopr in BOL nor Internet. Could you help me
please?
/RAM/|||A few months ago I could create backup using right-click menu, now I
cannot. What's going on?
/RAM/|||RAM (r_ahimsa_m@.poczta.onet.pl) writes:

Quote:

Originally Posted by

but I have another problem:
Cannot open backup device 'G:\DemoSQLServer.bak'. Operating system
error 5(Access denied.).
>
(Changing drive don't help.)
I have no problem with accessing drives from other applications. I had
no problems with SQL Server setup.


Is that a local drive or a network drive?

Presumably the service account for SQL Server does not have access to
this place. Keep in mind that SQL Server is a server application that
logs on its own.

Start SQL Server Configuraiton Manager. Select "SQL Server 2005 Services".
Find the SQL Server service you have problem with. Double-click. Here
you can see under which account SQL Server runs. If you change, you will
have to restart SQL Server.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx