Wickasitha's tech Blog

blogging everything

You might have occasion where you want to discover who finished second, the 10th most popular rock song, or the 5th highest paid employee. This is trival using nested TOP statements, but those can get pretty heavy if you are trying to get row 5,199,245

CREATE TABLE Employees
(
EmployeeID INT IDENTITY(1, 1)
PRIMARY KEY CLUSTERED,
LName VARCHAR(32),
Salary INT
)
GO

SET NOCOUNT ON
INSERT Employees(LName, Salary) VALUES(‘Bertrand’, 350000)
INSERT Employees(LName, Salary) VALUES(‘Le’ , 40000)
INSERT Employees(LName, Salary) VALUES(‘Smith’ , 50000)
INSERT Employees(LName, Salary) VALUES(‘Weathers’, 80000)
INSERT Employees(LName, Salary) VALUES(‘Martin’ , 53000)
INSERT Employees(LName, Salary) VALUES(‘VanWyck’ , 32000)
INSERT Employees(LName, Salary) VALUES(‘Gretzky’ , 30000)
INSERT Employees(LName, Salary) VALUES(‘Jambon’ , 30000)
INSERT Employees(LName, Salary) VALUES(‘DeNiro’ , 50000)
INSERT Employees(LName, Salary) VALUES(‘Albert’ , 40000)
INSERT Employees(LName, Salary) VALUES(‘Willis’ , 70000)

– solution #1: nested top, take aribitrary row

SELECT TOP 1 LName, Salary
FROM
(
SELECT TOP 7
LName, Salary FROM Employees
ORDER BY Salary DESC
) sub
ORDER BY Salary

– solution #2: nested top, order by lastname

SELECT TOP 1 LName, Salary
FROM
(
SELECT TOP 7
LName, Salary FROM Employees
ORDER BY Salary DESC, LName
) sub
ORDER BY Salary

– solution #3: nested top, take both rows

SELECT TOP 1 WITH TIES LName, Salary
FROM
(
SELECT TOP 7 WITH TIES
LName, Salary FROM Employees
ORDER BY Salary DESC
) sub
ORDER BY Salary

– solution #4: NOT IN, take both rows

SELECT TOP 1 WITH TIES LName, Salary
FROM Employees e
WHERE Salary NOT IN
(
SELECT TOP 6 WITH TIES Salary
FROM Employees
ORDER BY Salary DESC
)
ORDER BY e.Salary DESC

– solution #5: change NOT IN to OUTER JOIN

SELECT TOP 1 WITH TIES e.LName, e.Salary
FROM Employees e
LEFT OUTER JOIN
(
SELECT TOP 6 WITH TIES Salary
FROM Employees
ORDER BY Salary DESC
) e2
ON e.Salary = e2.salary
WHERE e2.salary IS NULL
ORDER BY e.Salary DESC

DROP TABLE Employees
GO

Getting Existing Spatial Databases Ready For Denali

With the availability of the new SQL Server code-named “Denali” CTP1 release, some of you will be moving existing SQL Server 2008 databases into the new server.  In order to enable the new spatial features in Denali, you will need to update the database compatibility level for existing SQL Server 2008 databases.  For Denali, the compatibility level is 110 and can be set with the following T-SQL:

–Set database compatibility level to SQL Server Code-Named “Denali”
ALTER DATABASE <database name>
SET COMPATIBILITY_LEVEL = 110;

You can get information on the compatibility level of all databases in a given SQL Server instance with the following stored procedure:

EXEC sp_helpdb

For more information on database compatibility levels see: http://msdn.microsoft.com/en-us/library/bb510680.aspx

With this release Microsoft have introduced the following enhancements:

  • Simplified and streamlined customer configuration and deployment
  • Lower cost of operation due to improved health model and reduced false alarms
  • Meets low-privilege constraints needed for financial and medical industries
  • New rules, monitors, and knowledge improvements
  • DMO-less deployment
  • SxS install with the old SQL 2000 management pack for customers with SQL 2K

For more information and download information go here:http://www.microsoft.com/downloads/details.aspx?FamilyID=8c0f970e-c653-4c15-9e51-6a6cadfca363&displaylang=en

SQL SERVER 2008 R2 EXPRESS NOW WITH 10GB DBS

SQL Server 2008 R2 Express is now available  for download from the SQL Server Express site.More importantly SQL Server 2008 R2 Express now supports 10 GB of storage per database.

Sql Server Reporting Services(SSRS) SDK for PHP

A new software developer kit (SDK) helps PHP developers work get new business intelligence capabilities with a free SQL Server Reporting Services SDK for PHP.

The library is designed to make simple for developers to call the SSRS remote APIs to perform the following operations:

  • Query for the list of reports available on the server
  • Query for the list of parameters required for each report with the list of valid values
  • Query the list of Formats supported by the Server
  • Execute a Report

The SDK is available on Codeplex.

About SQL Server and PHP

Microsoft SQL Server Driver for PHP allows PHP developers to access SQL Server databases. The SQL Server Driver for PHP relies on the Microsoft SQL Server ODBC Driver to handle the low-level communication with SQL Server.

How Its work..!

You can download the driver from the MSDN download site using this link.

For more information on the driver, see PHP on Windows, SQL Server Training Kits Updated.

SQL Optimization Tips

• Use views and stored procedures instead of heavy-duty queries.
This can reduce network traffic, because your client will send to
server only stored procedure or view name (perhaps with some
parameters) instead of large heavy-duty queries text. This can be used
to facilitate permission management also, because you can restrict
user access to table columns they should not see.

• Try to use constraints instead of triggers, whenever possible.
Constraints are much more efficient than triggers and can boost
performance. So, you should use constraints instead of triggers,
whenever possible.

• Use table variables instead of temporary tables.
Table variables require less locking and logging resources than
temporary tables, so table variables should be used whenever possible.
The table variables are available in SQL Server 2000 only.

• Try to use UNION ALL statement instead of UNION, whenever possible.
The UNION ALL statement is much faster than UNION, because UNION ALL
statement does not look for duplicate rows, and UNION statement does
look for duplicate rows, whether or not they exist.

• Try to avoid using the DISTINCT clause, whenever possible.
Because using the DISTINCT clause will result in some performance
degradation, you should use this clause only when it is necessary.

• Try to avoid using SQL Server cursors, whenever possible.
SQL Server cursors can result in some performance degradation in
comparison with select statements. Try to use correlated sub-query or
derived tables, if you need to perform row-by-row operations.

• Try to avoid the HAVING clause, whenever possible.
The HAVING clause is used to restrict the result set returned by the
GROUP BY clause. When you use GROUP BY with the HAVING clause, the
GROUP BY clause divides the rows into sets of grouped rows and
aggregates their values, and then the HAVING clause eliminates
undesired aggregated groups. In many cases, you can write your select
statement so, that it will contain only WHERE and GROUP BY clauses
without HAVING clause. This can improve the performance of your query.

• If you need to return the total table’s row count, you can use
alternative way instead of SELECT COUNT(*) statement.
Because SELECT COUNT(*) statement make a full table scan to return the
total table’s row count, it can take very many time for the large
table. There is another way to determine the total row count in a
table. You can use sysindexes system table, in this case. There is
ROWS column in the sysindexes table. This column contains the total
row count for each table in your database. So, you can use the
following select statement instead of SELECT COUNT(*): SELECT rows
FROM sysindexes WHERE id = OBJECT_ID(‘table_name’) AND indid < 2 So,
you can improve the speed of such queries in several times.

• Include SET NOCOUNT ON statement into your stored procedures to stop
the message indicating the number of rows affected by a T-SQL statement.
This can reduce network traffic, because your client will not receive
the message indicating the number of rows affected by a T-SQL statement.

• Try to restrict the queries result set by using the WHERE clause.
This can results in good performance benefits, because SQL Server will
return to client only particular rows, not all rows from the table(s).
This can reduce network traffic and boost the overall performance of
the query.

• Use the select statements with TOP keyword or the SET ROWCOUNT
statement, if you need to return only the first n rows.
This can improve performance of your queries, because the smaller
result set will be returned. This can also reduce the traffic between
the server and the clients.

• Try to restrict the queries result set by returning only the
particular columns from the table, not all table’s columns.
This can results in good performance benefits, because SQL Server will
return to client only particular columns, not all table’s columns.
This can reduce network traffic and boost the overall performance of
the query.
1.Indexes
2.avoid more number of triggers on the table
3.unnecessary complicated joins
4.correct use of Group by clause with the select list
5 In worst cases Denormalization

Index Optimization tips

• Every index increases the time in takes to perform INSERTS, UPDATES
and DELETES, so the number of indexes should not be very much. Try to
use maximum 4-5 indexes on one table, not more. If you have read-only
table, then the number of indexes may be increased.

• Keep your indexes as narrow as possible. This reduces the size of
the index and reduces the number of reads required to read the index.

• Try to create indexes on columns that have integer values rather
than character values.

• If you create a composite (multi-column) index, the order of the
columns in the key are very important. Try to order the columns in the
key as to enhance selectivity, with the most selective columns to the
leftmost of the key.

• If you want to join several tables, try to create surrogate integer
keys for this purpose and create indexes on their columns.

• Create surrogate integer primary key (identity for example) if your
table will not have many insert operations.

• Clustered indexes are more preferable than nonclustered, if you need
to select by a range of values or you need to sort results set with
GROUP BY or ORDER BY.

• If your application will be performing the same query over and over
on the same table, consider creating a covering index on the table.

• You can use the SQL Server Profiler Create Trace Wizard with
“Identify Scans of Large Tables” trace to determine which tables in
your database may need indexes. This trace will show which tables are
being scanned by queries instead of using an index.

• You can use sp_MSforeachtable undocumented stored procedure to
rebuild all indexes in your database. Try to schedule it to execute
during CPU idle time and slow production periods.
sp_MSforeachtable @command1=”print ‘?’ DBCC DBREINDEX (‘?’)”

You can use all .Net Framework Regular Expressions via MS Server CLR Integration. Microsoft recommends to use CLR Integration in scenarios where CLR-based programming can complement the expressive power of the T-SQL query language.This includes situations such as:

  • Performing complex calculations on a per-row basis over values stored in database tables.
  • Using procedural logic to evaluate tabular results that are then queried in the FROM clause of a SELECT or DML statement.

At the begin you have to allow MS SQL Server to use CLR Integration, i.e. to make possible usage of .Net assemblies and methods from them

sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

From here create assembly that is Wrapper for Regular Expression .Net classes. To create user defined function for MS SQL Server in C#/.Net you have just to

public partial class SqlRegularExpressions
  {
     [SqlFunction]
     public static bool Like(string text, string pattern)
     {
          Match match = Regex.Match(text, pattern);
          return (match.Value != String.Empty);
      }
}

Next step is assembly building.you have to deploy given assembly to MS SQL Server.

CREATE ASSEMBLY SqlRegularExpressions
from 'C:\Projects\ClassLibrary1\bin\Debug\SqlRegularExpressions.dll'
WITH PERMISSION_SET = SAFE

Assembly is registered and ready to use.now we may to use functionality from it. To bind assembly method with SQL Function

CREATE FUNCTION RegExpLike(@Text nvarchar(max), @Pattern nvarchar(255)) RETURNS BIT
AS EXTERNAL NAME SqlRegularExpressions.SqlRegularExpressions.[Like]


Now you can use RegExpLike function to check string matching to pattern with regular expression

-- get all products where title consists word that starts by 'D'
select * from Production.Product
where 1 = dbo.RegExpLike([Name], '\b(D\S+)')
regex

kick it on DotNetKicks.com

RSS Feeds

QR Code

qr code

QR code created by QR code Widget

Fun with .NET

Visitors

Your Ads Here
Promote your products