Showing posts with label Sql Server. Show all posts
Showing posts with label Sql Server. Show all posts

Friday, July 9, 2010

SQL SERVER – UDF – Function to Convert Text String to Title Case – Proper Case

Following function will convert any string to Title Case. I have this function for long time. I do not remember that if I wrote it myself or I modified from original source.

Run Following T-SQL statement in query analyzer:

SELECT dbo.udf_TitleCase('convert this string to title case!')


The output will be displayed in Results pan as follows:



Convert This String To Title Case!


T-SQL code of the function is:



CREATE FUNCTION udf_TitleCase (@InputString VARCHAR(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE @Index INT
DECLARE @Char CHAR(1)
DECLARE @OutputString VARCHAR(255)
SET @OutputString = LOWER(@InputString)
SET @Index = 2
SET @OutputString =
STUFF(@OutputString, 1, 1,UPPER(SUBSTRING(@InputString,1,1)))
WHILE @Index <= LEN(@InputString)
BEGIN
SET @Char = SUBSTRING(@InputString, @Index, 1)
IF @Char IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&','''','(')
IF @Index + 1 <= LEN(@InputString)
BEGIN
IF @Char != ''''
OR
UPPER(SUBSTRING(@InputString, @Index + 1, 1)) != 'S'
SET @OutputString =
STUFF(@OutputString, @Index + 1, 1,UPPER(SUBSTRING(@InputString, @Index + 1, 1)))
END
SET @Index = @Index + 1
END
RETURN ISNULL(@OutputString,'')
END

Friday, October 9, 2009

How to get the Column information for a Table using T-SQL

in this sample I am getting the column information for a table called ‘Account’:

SELECT     Columns.name AS ColumnName, ColumnTypes.name AS Type, Columns.prec AS Precision, Columns.scale AS Scale, 
Columns.isnullable AS IsNullable
FROM sys.sysobjects AS Tables INNER JOIN
sys.syscolumns AS Columns ON Columns.id = Tables.id INNER JOIN
sys.systypes AS ColumnTypes ON Columns.xtype = ColumnTypes.xtype
WHERE (Tables.type = 'U') AND (Tables.name = N'Account')
ORDER BY ColumnName

Monday, March 9, 2009

Writing recursive queries in sql server 2000/2005

In SQL Server 2000 there is no simple way to create recursive queries that have several levels of data (hierarchical data). Generally a recursive query is needed when you have a parent and child data stored in the same table. One example may be employee data where all employee data is stored in one Employee table and there is an indicator that specifies the employees supervisor that points back to another record in the same table. This is done quite often for other data as well.

To query this data to find the employee and supervisor is pretty easy. The query would be:



SELECT e1.EmpId, e1.FirstName, e1.LastName,
e1.SupervisorID, e2.FirstName AS SupFirstName, e2.LastName
AS SupLastNameFROM Employee e1 LEFT JOIN Employee e2
ON e1.SupervisorID = e2.EmpId

So you can see this is pretty simple to just get this level of data, but what if you want to find out all of the direct and indirect reports of a particular employee.

C programmers use recursive programming techniques for traversing tree structures. The same can be implemented in T-SQL using recursive stored procedure calls.

Consider the employee table of an organization, that stores all the employee records. Each employee is linked to his/her manager by a manger ID. This table can be represented using the following CREATE TABLE statement:



CREATE TABLE dbo.Emp
(
EmpID int PRIMARY KEY,
EmpName varchar(30),
MgrID int FOREIGN KEY REFERENCES Emp(EmpID)
)

Notice that, EmpID is decalred as a primary key, and the MgrID column is declared as a foreign key constraint, that references the EmpID column of the same table, that is, a self referencing table. This is so, because all employees and managers are stored in the same table.

Now what all we need is a stored procedure that calls itself recursively. You should be aware of a limitation imposed by SQL Server though. A stored procedure can nest itself upto a maximum of 32 levels. If you exceed this limit, you will receive the following error:
Server: Msg 217, Level 16, State 1, Procedure , Line 1 Maximum stored procedure nesting level exceeded (limit 32).

The SQL server 2005 microsoft come up with Common Table Expressions for writing Recursive queries.

A common table expression (CTE) provides the significant advantage of being able to reference itself, thereby creating a recursive CTE. A recursive CTE is one in which an initial CTE is repeatedly executed to return subsets of data until the complete result set is obtained.


A query is referred to as a recursive query when it references a recursive CTE. Returning hierarchical data is a common use of recursive queries, for example: Displaying employees in an organizational chart, or data in a bill of materials scenario in which a parent product has one or more components and those components may, in turn, have subcomponents or may be components of other parents.


A recursive CTE can greatly simplify the code required to run a recursive query within a SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. In earlier versions of SQL Server, a recursive query usually requires using temporary tables, cursors, and logic to control the flow of the recursive steps.

recursive CTE in Transact-SQL is similar to recursive routines in other programming languages. Although a recursive routine in other languages returns a scalar value, a recursive CTE can return multiple rows.


A recursive CTE consists of three elements:
1. Invocation of the routine.

The first invocation of the recursive CTE consists of one or more CTE_query_definitions joined by UNION ALL, UNION, EXCEPT, or INTERSECT operators. Because these query definitions form the base result set of the CTE structure, they are referred to as anchor members.CTE_query_definitions are considered anchor members unless they reference the CTE itself. All anchor-member query definitions must be positioned before the first recursive member definition, and a UNION ALL operator must be used to join the last anchor member with the first recursive member.
2. Recursive invocation of the routine.

The recursive invocation includes one or more CTE_query_definitions joined by UNION ALL operators that reference the CTE itself. These query definitions are referred to as recursive members.
3. Termination check.

The termination check is implicit; recursion stops when no rows are returned from the previous invocation.

The recursive CTE structure must contain at least one anchor member and one recursive member. The following pseudocode shows the components of a simple recursive CTE that contains a single anchor member and single recursive member.


WITH cte_name ( column_name [,...n] )
AS
(
CTE_query_definition –- Anchor member is defined.
UNION ALL
CTE_query_definition –- Recursive member is defined referencing cte_name.
)
-- Statement using the CTE
SELECT * FROM cte_name

Example:

The following example shows the semantics of the recursive CTE structure by returning a hierarchical list of employees, starting with the highest ranking employee, in the company. The statement that executes the CTE limits the result set to employees in the Research and Development Group.



WITH DirectReports (ManagerID, EmployeeID, Title, DeptID, Level)
AS
(-- Anchor member definition
SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID,
0 AS Level FROM HumanResources.Employee AS e INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh
ON e.EmployeeID = edh.EmployeeID AND edh.EndDate IS NULL WHERE ManagerID IS NULL
UNION ALL
-- Recursive member definition
SELECT e.ManagerID, e.EmployeeID, e.Title, edh.DepartmentID, Level + 1 FROM HumanResources.Employee AS e
INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh
ON e.EmployeeID = edh.EmployeeID AND edh.EndDate IS NULL INNER JOIN DirectReports AS d
ON e.ManagerID = d.EmployeeID)
-- Statement that executes the CTE
SELECT ManagerID, EmployeeID, Title, LevelFROM DirectReportsINNER JOIN HumanResources.Department AS dp ON DirectReports.DeptID = dp.DepartmentID
WHERE dp.GroupName = N'Research and Development' OR Level = 0;

Monday, February 9, 2009

Transaction Recovery

Every Microsoft® SQL Server™ 2000 database has a transaction log that records data modifications made in the database. The log records the start and end of every transaction and associates each modification with a transaction. An instance of SQL Server stores enough information in the log to either redo (roll forward) or undo (roll back) the data modifications that make up a transaction. Each record in the log is identified by a unique log sequence number (LSN). All of the log records for a transaction are chained together.

An instance of SQL Server records many different types of information in the transaction log. Instances of SQL Server 2000 primarily log the logical operations performed. The operation is reapplied to roll forward a modification, and the opposite of the logical operation is performed to roll back a modification.

Each instance of SQL Server controls when modifications are written from its data buffers to disk. An instance of SQL Server may cache modifications in buffers for a period of time to optimize disk writes. A buffer page that contains modifications that have not yet written to disk is known as a dirty page. Writing a dirty buffer page to disk is called flushing the page. When modifications are cached, care must be taken to ensure that no data modification is flushed before the corresponding log image is written to the log file. This could create a modification that could not be rolled back if necessary. To ensure that they can recover all modifications, instances of SQL Server use a write-ahead log, which means that all log images are written to disk before the corresponding data modification.

A commit operation forces all log records for a transaction to the log file so that the transaction is fully recoverable even if the server is shut down. A commit operation does not have to force all the modified data pages to disk as long as all the log records are flushed to disk. A system recovery can roll the transaction forward or backward using only the log records.

Periodically, each instance of SQL Server ensures that all dirty log and data pages are flushed. This is called a checkpoint. Checkpoints reduce the time and resources needed to recover when an instance of SQL Server is restarted. For more information on checkpoint processing, see Checkpoints and the Active Portion of the Log.

Rolling Back an Individual Transaction
If any errors occur during a transaction, the instance of SQL Server uses the information in the log file to roll back the transaction. This rollback does not affect the work of any other users working in the database at the same time. Usually, the error is returned to the application, and if the error indicates a possible problem with the transaction, the application issues a ROLLBACK statement. Some errors, such as a 1205 deadlock error, roll back a transaction automatically. If anything stops the communication between the client and an instance of SQL Server while a transaction is active, the instance rolls back the transaction automatically when notified of the stoppage by the network or operating system. This could happen if the client application terminates, if the client computer is shut down or restarted, or if the client network connection is broken. In all of these error conditions, any outstanding transaction is rolled back to protect the integrity of the database.

Recovery of All Outstanding Transactions at Start-up
It is possible for an instance of SQL Server to sometimes stop processing (for example, if an operator restarts the server while users are connected and working in databases). This can create two problems:


  • There may be an unknown number of SQL Server transactions partially completed at the time the instance stopped. These incomplete transactions need to be rolled back.

  • There may be an unknown number of data modifications recorded in the SQL Server database log files, but the corresponding modified data pages were not flushed to the data files before the server stopped. Any committed modifications must be rolled forward.

When an instance of SQL Server is started, it must find out if either of these conditions exist and address them. The following steps are taken in each SQL Server database that is in the instance:


  1. The LSN of the last checkpoint is read from the database boot block along with the Minimum Recovery LSN.
  2. The transaction log is scanned from the Minimum Recovery LSN to the end of the log. All committed dirty pages are rolled forward by redoing the logical operation recorded in the log record.
  3. The instance of SQL Server then scans backward through the log file rolling back all uncompleted transactions by applying the opposite of the logical operation recorded in the log records.
The RESTORE statement also uses this type of recovery, unless a user specifies the NORECOVERY option. When restoring a sequence of database, differential, or log backups to recover a database to a point of failure, you specify NORECOVERY on all RESTORE statements except when restoring the last log backup. When the last backup in the sequence is restored, the RESTORE statement also has to ensure that all uncompleted transactions are rolled back. You specify the RECOVERY option on this RESTORE statement, in which case it uses the same logic as the startup recovery process to roll back all transactions that are still marked incomplete at the end of the last log.

Friday, January 23, 2009

How to perform case sensitive searches in SQL Server?

A default SQL Server installation is case insensitive, which means that SQL Server will not differentiate between upper and lower case characters/letters. That is, "Magic" is the same as "MAGIC" or "magic".
Let’s see why one would want to perform case sensitive searches. One classic example is password comparisons. People use a combination of upper and lower case (mixed case) characters in their passwords, just to make the passwords difficult to guess. But there is no point in doing that, if the database disregards the case.
To keep the users happy, and their passwords secure, programmers prefer case sensitive comparisons in this case.
So we can achieve the goal by Converting data to binary type before comparison:When you convert a character to binary or varbinary datatype, that character's ASCII value gets represented in binary. Since, 'A' and 'a' have different ASCII values, when you convert them to binary, the binary representations of these values don't match, and hence the case sensitive behavior.
Example :



IF EXISTS
(SELECT 1 FROM AuthenticCustomers
WHERE CAST(UserID AS varbinary(20)) = CAST( AS varbinary(20))
AND CAST(User_Password AS varbinary(25)) = CAST( AS varbinary(25)))

BEGIN
PRINT 'Authentic User'
END
ELSE
BEGIN
PRINT 'Invalid User or Password'
END

Monday, September 15, 2008

General network error. Check your network documentation.

There is a lot of people out there complaining about SQL Server returning a General network error while executing a command form ADO.NET version 1.1 or 1.0. Since it is a General network error, it seems to me that there are as many reasons for this error as there are people having it. one fine day I too experienced the same so I googled it but saveral posts in several blogs leads to various solutions like append max pool size = 7500, to your connection string will solve the issue or setting the command timeout to anything but zero totally fixes it.

I tried all of them but still i experienced the same error intermittently. Finally i found that The calling asp.net page creates an ojbect which opens the connection over and over and relies on the destruct method of the database object to do the closing so I am assuming our problem is related to this but I have not been able to reproduce it reliably so I can't be sure this is the cause of the problem.

then i found this microsoft KB article

it says that In the current design, after an application role is enabled on a client connection to SQL Server, you cannot reset the security context of that connection. Therefore, when the user ends the SQL Server session and disconnects from the server, the session is not reusable. However, OLE DB resource pooling returns the closed connection to the pool, and the error occurs when that connection is reused and the client application tries to reset the connection's security context by calling sp_setapprole again.

WORKAROUND

The only available workaround is to disable OLE DB Resource Pooling, which ADO uses by default. You can do this by adding "OLE DB Services = -2" to the ADO Connection string, as shown here: 'For SQLOLEDB provider
'strConnect = "Provider=SQLOLEDB;server=SQL7Web;OLE DB Services = -2;uid=AppUser;pwd=AppUser;initial catalog=northwind"

' For MSDASQL provider
'strConnect = "DSN=SQLNWind;UID=Test;PWD=Test; OLE DB Services= -2"


Pooling can be disabled for the SQL Server .Net Data Provider by adding "Pooling=False" to the connection string.

although that solves my issue but what if the connection pooling is needed ????

Thursday, August 28, 2008

Cross Tab queries , Converting Rows to Columns

Hi all,

While browsing on the net I got a really good article by Jeff Moden on Cross Tab queries , Converting Rows to Columns . Hats off to jeff for this beautiful article. Some part of it that I feel was really very helpful for me I am reproducing it here for my future reference and I recommend you guys to read the complete series
here

Cross Tab queries , Converting Rows to Columns
Sometimes it is necessary to rotate results so that [the data in] columns are presented horizontally and [the data in] rows are presented vertically. This is known as creating a cross-tab report, or rotating data.

In other words, you can use a Cross Tab or Pivot to convert or transpose information from rows to columns.
A simple introduction to Cross Tabs:

The Cross Tab Report example from Books Online is very simple and easy to understand. I've shamelessly borrowed from it to explain this first shot at a Cross Tab

The Test Data

Basically, the table and data looks like this...



--===== Sample data #1 (#SomeTable1)
--===== Create a test table and some data
CREATE TABLE #SomeTable1
(
Year SMALLINT,
Quarter TINYINT,
Amount DECIMAL(2,1)
)
GO
INSERT INTO #SomeTable1
(Year, Quarter, Amount)
SELECT 2006, 1, 1.1 UNION ALL
SELECT 2006, 2, 1.2 UNION ALL
SELECT 2006, 3, 1.3 UNION ALL
SELECT 2006, 4, 1.4 UNION ALL
SELECT 2007, 1, 2.1 UNION ALL
SELECT 2007, 2, 2.2 UNION ALL
SELECT 2007, 3, 2.3 UNION ALL
SELECT 2007, 4, 2.4 UNION ALL
SELECT 2008, 1, 1.5 UNION ALL
SELECT 2008, 3, 2.3 UNION ALL
SELECT 2008, 4, 1.9
GO

Every row in the code above is unique in that each row contains ALL the information for a given quarter of a given year. Unique data is NOT a requirement for doing Cross Tabs... it just happens to be the condition that the data is in. Also, notice that the 2nd quarter for 2008 is missing.
The goal is to make the data look more like what you would find in a spreadsheet... 1 row for each year with the amounts laid out in columns for each quarter with a grand total for the year. Kind of like this...

... and, notice, we've plugged in a "0" for the missing 2nd quarter of 2008.

Year 1st Qtr 2nd Qtr 3rd Qtr 4th Qtr Total
------ ------- ------- ------- ------- -----
2006 1.1 1.2 1.3 1.4 5.0
2007 2.1 2.2 2.3 2.4 9.0
2008 1.5 0.0 2.3 1.9 5.7

The KEY to Cross Tabs!
Let's start out with the most obvious... we want a Total for each year. This isn't required for Cross Tabs, but it will help demonstrate what the key to making a Cross Tab is.
To make the Total, we need to use the SUM aggregate and a GROUP BY

... like this...




--===== Simple sum/total for each year
SELECT Year,
SUM(Amount) AS Total
FROM #SomeTable1
GROUP BY Year
ORDER BY Year


And, that returns the following...

Year Total
------ ----------------------------------------
2006 5.0
2007 9.0
2008 5.7


Not so difficult and really nothing new there. So, how do we "pivot" the data for the Quarter?
Let's do this by the numbers...
1. How many quarters are there per year? Correct, 4.
2. How many columns do we need to show the 4 quarters per year? Correct, 4.
3. How many times do we need the Quarter column to appear in the SELECT list to make it show up 4 times per year? Correct, 4.
4. Now, look at the total column... it gives the GRAND total for each year. What would we have to do to get it to give us, say, the total just for the first quarter for each year? Correct... we need a CASE statement inside the SUM.
Number 4 above is the KEY to doing this Cross Tab... It should be a SUM and it MUST have a CASE to identify the quarter even though each quarter only has 1 value. Yes, if each quarter had more than 1 value, this would still work! If any given quarter is missing, a zero will be substituted.


To emphasize, each column for each quarter is just like the Total column, but it has a CASE statement to trap info only for the correct data for each quarter's column. Here's the code...




--===== Each quarter is just like the total except it has a CASE
-- statement to isolate the amount for each quarter.
SELECT Year,
SUM(CASE WHEN Quarter = 1 THEN Amount ELSE 0 END) AS [1st Qtr],
SUM(CASE WHEN Quarter = 2 THEN Amount ELSE 0 END) AS [2nd Qtr],
SUM(CASE WHEN Quarter = 3 THEN Amount ELSE 0 END) AS [3rd Qtr],
SUM(CASE WHEN Quarter = 4 THEN Amount ELSE 0 END) AS [4th Qtr],
SUM(Amount) AS Total
FROM #SomeTable1
GROUP BY Year

... and that gives us the following result in the text mode (modified so it will fit here)...
Year 1st Qtr 2nd Qtr 3rd Qtr 4th Qtr Total
------ ------- ------- ------- ------- -----
2006 1.1 1.2 1.3 1.4 5.0
2007 2.1 2.2 2.3 2.4 9.0
2008 1.5 .0 2.3 1.9 5.7


Also notice... because there is only one value for each quarter, we could have gotten away with using MAX instead of SUM.
For most applications, that's good enough. If it's supposed to represent the final output, we might want to make it a little prettier. The STR function inherently right justifies, so we can use that to make the output a little prettier.




--===== We can use the STR function to right justify data and make it prettier.
-- Note that this should really be done by the GUI or Reporting Tool and
-- not in T-SQL
SELECT Year,
STR(SUM(CASE WHEN Quarter = 1 THEN Amount ELSE 0 END),5,1) AS [1st Qtr],
STR(SUM(CASE WHEN Quarter = 2 THEN Amount ELSE 0 END),5,1) AS [2nd Qtr],
STR(SUM(CASE WHEN Quarter = 3 THEN Amount ELSE 0 END),5,1) AS [3rd Qtr],
STR(SUM(CASE WHEN Quarter = 4 THEN Amount ELSE 0 END),5,1) AS [4th Qtr],
STR(SUM(Amount),5,1) AS Total
FROM #SomeTable1
GROUP BY Year


The code above gives us the final result we were looking for...
Year 1st Qtr 2nd Qtr 3rd Qtr 4th Qtr Total
------ ------- ------- ------- ------- -----
2006 1.1 1.2 1.3 1.4 5.0
2007 2.1 2.2 2.3 2.4 9.0
2008 1.5 0.0 2.3 1.9 5.7


Just to emphasize what the very simple KEY to making a Cross Tab is... it's just like making a Total using SUM and Group By, but we've added a CASE statement to isolate the data for each Quarter.

Tuesday, August 26, 2008

Using REPLACE in an UPDATE statement

hi all ,

Many times we need to update the records in our SQL tables in a way like
1. Removing unwanted spaces
2. Replacing some required text pattern from our existing records.

the easiest way to do that is by using REPLACE in an UPDATE statement :

for example :

if a record is " its a simple script" and we need to update it as " its a really simple script"

all we need to do is


update table_name set column = Replace(column ,'simple', 'really simple')


and that's it ... now where ever in the column in question holds 'Simple' in any record is now updated to 'really simple'

enjoy :-)

Friday, August 22, 2008

Ms Sql Server Create Table From Another Table

For the purpose we will use the method SELECT INTO :

This method is used when table is not created earlier and needs to be created when data from one table is to be inserted into newly created table from another table. New table is created with same data types as selected columns.



---- Create new table and insert into table using SELECT INSERT

SELECT Column1, Column2 INTO NewTable FROM oldTable WHERE 1 = 2


Th sql above will copy the structure only

To copy selected data too we need to do the same as :


---- Create new table and insert into table using SELECT INSERT

SELECT Column1, Column2 INTO NewTable FROM oldTable WHERE

Monday, July 14, 2008

SQL Server Update table with inner join : update one table based on the contents of another table

Many times we need to update the contents of one table based on the contents of another table.

Have you ever found yourself in such situation ?

Well the simplest approach for that is by using the aliases.

For example if we wish to update a table tableA based on the contents of the table tableB then by using aliases we can do it in the following way:




Update a set a.field = b.field from tableA a inner join tableB b on a.primaryKey=b.foreignkey

And that’s it.

Wednesday, July 2, 2008

What are types of compatibility inVB6?

There are three possible project compatibility settings: - No compatibility - Project compatibility - Binary compatibility No Compatibility With this setting, new class ID’s, new interface ID’s and a new type library ID will be generated by VB each time the ActiveX component project is compiled. This will cause any compiled client components to fail(with error 429!) and report a missing reference to the `VB ActiveX Test component’ when a client project is loaded in the VB IDE. Note: Use this setting to compile the initial release of a component to other developers. Project Compatibility With this setting, VB will generate new interface ID’s for classes whose interfaces have changed, but will not change the class ID’s or the type library ID. This will still cause any compiled client components to fail(with error 429!)but will not report a missing reference to the `VB ActiveX Test component’ when a client project is loaded in the VB IDE. Recompilation of client components will restore them to working order again. Note: Use this setting during the initial development and testing of a component within the IDE and before the component is released to other developers. Binary Compatibility VB makes it possible to extend an existing class or interface by adding new methods and properties etc. And yet still retain binary compatibility. It can do this, because it silently creates a new interface ID for the extended interface and adds registration code to register the original interface ID but with a new forward key containing the value of the new interface ID.COM will then substitute calls having the old ID with the new ID and hence applications built against the old interface will continue to work(assuming the inner workings of the component remain backward compatible!). With this settings, VB will not change any of the existing class, interface or type library ID’s, however in order that it can do so, VB requires the project to specify an existing compiled version that it can compare against to ensure that existing interfaces have not been broken.

What is CODE Access security?

To help protect computer systems from malicious mobile code, to allow code from unknown origins to run with protection, and to help prevent trusted code from intentionally or accidentally compromising security, the .NET Framework provides a security mechanism called code access security. Code access security allows code to be trusted to varying degrees depending on where the code originates and on other aspects of the code's identity. Code access security also enforces the varying levels of trust on code, which minimizes the amount of code that must be fully trusted in order to run. Using code access security can reduce the likelihood that your code can be misused by malicious or error-filled code. It can reduce your liability because you can specify the set of operations your code should be allowed to perform as well as the operations your code should never be allowed to perform. Code access security can also help minimize the damage that can result from security vulnerabilities in your code.

All managed code that targets the common language runtime receives the benefits of code access security, even if that code does not make a single code access security call.

Tuesday, June 24, 2008

Methods to generate random number in SQL Server

There are many methods to generate random number in SQL Server.


--Method 1 : Generate Random Numbers (Int) between Range
-- Create the variables for the random number generation
DECLARE @Random INT
DECLARE @Upper INT
DECLARE @Lower INT
-- This will create a random number between 1 and 999
SET @Lower = 1 -- The lowest random number
SET @Upper = 999 -- The highest random number
SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
SELECT @Random

--Method 2 : Generate Random Float Numbers
SELECT RAND( (DATEPART(mm, GETDATE()) * 100000 )+ (DATEPART(ss, GETDATE()) * 1000 )+ DATEPART(ms, GETDATE()) )

--Method 3 : Random Numbers Quick Scripts

-- random float from 0 up to 20 - [0, 20]
SELECT 20*RAND()
-- random float from 10 up to 30 - [10, 30]
SELECT 10 + (30-10)*RAND()
--random integer BETWEEN 0 AND 20 - [0, 20]
SELECT CONVERT(INT, (20+1)*RAND())
--random integer BETWEEN 10 AND 30 - [10, 30]
SELECT 10 + CONVERT(INT, (30-10+1)*RAND())

--Method 4 : Random Numbers (Float, Int) Tables Based with Time

DECLARE @t TABLE( randnum float )
DECLARE @cnt INT
SET @cnt = 0
WHILE @cnt <=10000
BEGIN
SET @cnt = @cnt + 1
INSERT INTO @tSELECT RAND( (DATEPART(mm, GETDATE()) * 100000 )+ (DATEPART(ss, GETDATE()) * 1000 )+ DATEPART(ms, GETDATE()) )
END

SELECT randnum, COUNT(*)FROM @t GROUP BY randnum

--Method 5 : Random number on a per row basis
--The distribution is pretty good however there are the occasional peaks.
--If you want to change the range of values just change the 1000 to the maximum
--value you want. Use this as the source of a report server report and chart the
--results to see the distribution

SELECT randomNumber, COUNT(1) countOfRandomNumber FROM (SELECT ABS(CAST(NEWID() AS binary(6)) %1000) + 1 randomNumberFROM sysobjects) sample GROUP BY randomNumber ORDER BY randomNumber

How to select records randomely from the SQL Server table.

There are many times when we need to select some records randomely from the SQL Server table.

For that purpose there are many ways that can be utilized for the same. they're especially effective when you wish to add dynamism to a site. For instance, you could randomly select a product to present as Today's Featured Product, or QA could generate a random call list to gauge customer satisfaction levels.

But the snag is that SQL doesn't permit the selection of random rows. then howe to do that ?
But you don't need to worry becaues the good news is that there's a simple trick to getting this functionality to work in SQL.

The solution is based on the uniqueidentifier data type. Unique identifiers, popularily known as Guaranteed Unique Identifiers (GUIDs), look something like this:

4C34AA46-2A5A-4F8C-897F-02354728C7B0

SQL Server uses GUIDs in many contexts, perhaps most notably in replication. You can use them when normal incrementing identity columns won't provide a sufficient range of keys. To do this, you create a column of type uniqueidentifier whose default value is NewID(), something like this:

CREATE TABLE MyNewTable
(
PK uniqueidentifier NOT NULL DEFAULT NewID(),
AnotherColumn varchar(50) NOT NULL,
. . .

This function is just the ticket to solve our random rows problem. We can simply call NewID() as a virtual column in our query, like this:

Select top , NEWID() AS RANDOM from TABLE order by RANDOM

you can now get the number of records selected randomly.

and that's what we want .

so cheers ....

Tuesday, June 10, 2008

How do we can format money or decimal with commas?

Sometimes we want to have our money fields properly formatted with commas like this: 12,345,678.9999

For the same purpose we can use the CONVERT function and give a value between 0 and 2 to the style and the format will be displayed based on that style selection

Here is an example:

DECLARE @value MONEYSELECT @v = 12345678.6666
SELECT CONVERT(VARCHAR,@value ,0) --12345678.67 value is Rounded but no formatting is done
SELECT CONVERT(VARCHAR,@value ,1) --12,345,678.67 Formatted with commas
SELECT CONVERT(VARCHAR,@value ,2) --12345678.6666 No formatting

Now If we have a decimal field it doesn't work with the convert function. The work around in this case is to convert it to money and then follow the above method.

For example:

DECLARE @TargetValue DECIMAL (36,10)
SELECT @TargetValue = 12345678.6666
SELECT CONVERT(VARCHAR,CONVERT(MONEY,@TargetValue ),1) --12,345,678.67 Formatted with commas

how to remove time component from a datetime value

What if I want to remove the time component from a datetime value ?

That is to say I want 2008-04-18 00:00:00.000 intead of 2008-04-18 13:46:57.983

Now since values with the datetime data type are stored internally by the SQL Server 2005 Database Engine as two 4-byte integers. The first 4 bytes store the number of days before or after the base date: January 1, 1900. The base date is the system reference date. The other 4 bytes store the time of day represented as the number of 1/300-second units after midnight.
reference : http://msdn2.microsoft.com/en-us/library/ms187819.aspx

so the simplest way of doing this I found is :

SELECT CONVERT(DATETIME,CONVERT(INT,datetimevalue))

Wednesday, April 9, 2008

How to find all the stored procedures that reference a specific object ?

Usually, people tries to find all the stored procedures that reference a specific object. This object could be any table, view or even any text that is placed in the procedure, In all such cases this post will be really of much help to all of them.

SQL SERVER 2000

Let's say you are searching for 'objectName' in all your stored procedures then all you have to do is :

SELECT ROUTINE_NAME, ROUTINE_DEFINITION FROM

INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%objectName%'
AND ROUTINE_TYPE='PROCEDURE'

Another way to perform a search is through the system table syscomments:

SELECT OBJECT_NAME(id) FROM syscomments
WHERE [text] LIKE '%objectName%'
AND OBJECTPROPERTY(id, 'IsProcedure') = 1
GROUP BY OBJECT_NAME(id)

Now, why to use GROUP BY? Well, there is a curious distribution of the procedure text in system tables if the procedure is greater than 8KB. So, the above makes sure that any procedure name is only returned once, even if multiple rows in or syscomments draw a match. But, that begs the question, what happens when the text you are looking for crosses the boundary between rows? Here is a method to create a simple stored procedure that will do this, by placing the search term (in this case, 'objectName') at around character 7997 in the procedure. This will force the procedure to span more than one row in syscomments, and will break the word 'objectName' up across rows.

Run the following query in Query Analyzer, with results to text (CTRL+T):

SET NOCOUNT ON
SELECT 'SELECT '''+REPLICATE('x', 7936)+'objectName' SELECT REPLICATE('x', 500)+''''

This will yield two results. Copy them and inject them here:

CREATE PROCEDURE dbo.x
AS
BEGIN
SET NOCOUNT ON
<<>>
END
GO

Now, try and find this stored procedure in INFORMATION_SCHEMA.ROUTINES or syscomments using the same search filter as above. The former will be useless, since only the first 8000 characters are stored here. The latter will be a little more useful, but initially, will return 0 results because the word 'objectName' is broken up across rows, and does not appear in a way that LIKE can easily find it. So, we will have to take a slightly more aggressive approach to make sure we find this procedure. Your need to do this, by the way, will depend partly on your desire for thoroughness, but more so on the ratio of stored procedures you have that are greater than 8KB. In all the systems that I manage, I don't have more than a handful that approach this size, so this isn't something I reach for very often. Maybe for you it will be more useful. First off, to demonstrate a little better (e.g. by having more than one procedure that exceeds 8KB), let's create a second procedure just like above. Let's call it dbo.y, but this time remove the word 'objectName' from the middle of the SELECT line.

CREATE PROCEDURE dbo.y
AS
BEGIN
SET NOCOUNT ON
<<>>
END
GO

Basically, what we're going to do next is loop through a cursor, for all procedures that exceed 8KB. We can get this list as follows:

SELECT OBJECT_NAME(id)
FROM syscomments
WHERE OBJECTPROPERTY(id, 'IsProcedure') = 1
GROUP BY OBJECT_NAME(id)
HAVING COUNT(*) > 1

We'll need to create a work table to hold the results as we loop through the procedure, and we'll need to use UPDATETEXT to append each row with the new 8000-or-less chunk of the stored procedure code.

-- create temp table
CREATE TABLE #temp ( Proc_id INT, Proc_Name SYSNAME, Definition NTEXT )
-- get the names of the procedures that meet our criteria
INSERT #temp(Proc_id, Proc_Name)
SELECT id, OBJECT_NAME(id)
FROM syscomments
WHERE OBJECTPROPERTY(id, 'IsProcedure') = 1
GROUP BY id, OBJECT_NAME(id)
HAVING COUNT(*) > 1

-- initialize the NTEXT column so there is a pointer
UPDATE #temp SET Definition = ' '
-- declare local variables
DECLARE @txtPval binary(16), @txtPidx INT, @curName SYSNAME, @curtext NVARCHAR(4000)

-- set up a cursor, we need to be sure this is in the correct order
-- from syscomments (which orders the 8KB chunks by colid)

DECLARE c CURSOR
LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
SELECT OBJECT_NAME(id), text
FROM syscomments s
INNER JOIN #temp t
ON s.id = t.Proc_id
ORDER BY id, colid OPEN c FETCH NEXT FROM c INTO @curName, @curtext

-- start the loop
WHILE (@@FETCH_STATUS = 0)
BEGIN
-- get the pointer for the current procedure name / colid

SELECT @txtPval = TEXTPTR(Definition)
FROM #temp
WHERE Proc_Name = @curName

-- find out where to append the #temp table's value

SELECT @txtPidx = DATALENGTH(Definition)/2
FROM #temp
WHERE Proc_Name = @curName
-- apply the append of the current 8KB chunk
UPDATETEXT #temp.definition @txtPval @txtPidx 0 @curtext
FETCH NEXT FROM c INTO @curName, @curtext
END
-- check what was produced
SELECT Proc_Name, Definition, DATALENGTH(Definition)/2
FROM #temp
-- check our filter
SELECT Proc_Name, Definition
FROM #temp
WHERE definition LIKE '%objectName%'
-- clean up
DROP TABLE #temp
CLOSE c
DEALLOCATE c

SQL SERVER 2005
In SQL Server 2005 there are new functions like OBJECT_DEFINITION, which returns the whole text of the procedure. Also, there is a new catalog view, sys.sql_modules, which also holds the entire text, and INFORMATION_SCHEMA.ROUTINES has been updated so that the ROUTINE_DEFINITION column also contains the full text of the procedure. So, any of the following queries will work to perform this search in SQL Server 2005:


SELECT Name FROM sys.procedures
WHERE OBJECT_DEFINITION(object_id)
LIKE '%objectName%'

SELECT OBJECT_NAME(object_id) FROM sys.sql_modules
WHERE Definition LIKE '%objectName%'
AND OBJECTPROPERTY(object_id, 'IsProcedure') = 1

SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%objectName%'
AND ROUTINE_TYPE = 'PROCEDURE'


Hats off for the beautifully explained and really useful article at Aspfaq.

Wednesday, December 26, 2007

Adding the single quotes into sql server statements...

Hi,

Yesterday one of my junior came to me and ask a simple question :

How to add the single quotes into sql server statements ?????

lets say I want to update an existing record. The sql for it is below:
update sampletable set field='data' where id='#'
ok, very simple . Now what if the data includes a single quote in it? Something like “vishal’s store”.

the resulting sql query looks like this:
update tblLocation set Loc_Name='Vishal's Store' where id='Vishal25648'
this will generate errors in the sql statement, because after the single quote is encountered the sql parser looks for a where clause.

Any ideas of how to get around this? And special character codes in sql for single quote?

Although this is a simple issue but many of novices are still unaware and tried the backslashes and all to get it done.

But the answer is as simple as the question J

The answer is this:
update tblLocation set Loc_Name='Vishal''s Store' where id='Vishal25648'
All you need is to add 1 (one) extra single quote before the intended single quote. Sounds simple isn’t it.
Note: this answer is specific to sql server 2000. The syntax might be different for oracle, sybase, or others.

Saturday, November 3, 2007

Tsql Select optional clauses

COMPUTE Clause
Generates totals that appear as additional summary columns at the end of the result set. When used with BY, the COMPUTE clause generates control-breaks and subtotals in the result set. You can specify COMPUTE BY and COMPUTE in the same query.
Syntax
[ COMPUTE { { AVG COUNT MAX MIN STDEV STDEVP VAR VARP SUM } (expression) } [,...n] [ BY expression [,...n] ]]
Arguments
AVG COUNT MAX MIN STDEV STDEVP VAR VARP SUM
Specifies the aggregation to be performed. These row aggregate functions are used with the COMPUTE clause.

Row aggregate function
Result
AVG
Average of the values in the numeric expression
COUNT
Number of selected rows
MAX
Highest value in the expression
MIN
Lowest value in the expression
STDEV
Statistical standard deviation for all values in the expression
STDEVP
Statistical standard deviation for the population for all values in the expression
SUM
Total of the values in the numeric expression
VAR
Statistical variance for all values in the expression
VARP
Statistical variance for the population for all values in the expression
There is no equivalent to COUNT(*). To find the summary information produced by GROUP BY and COUNT(*), use a COMPUTE clause without BY.
These functions ignore null values.
The DISTINCT keyword is not allowed with row aggregate functions when they are specified with the COMPUTE clause.
When you add or average integer data, SQL Server treats the result as an int value, even if the data type of the column is smallint or tinyint

FOR BROWSE Clause
Specifies that updates be allowed while viewing data in client applications using DB-Library.
A table can be browsed in an application under these conditions:
The table includes a time-stamped column (defined with the timestamp data type).
The table has a unique index.
The FOR BROWSE option is at the end of the SELECT statement(s) sent to SQL Server.

Note It is not possible to use the HOLDLOCK in a SELECT statement that includes the FOR BROWSE option.

The FOR BROWSE option cannot appear in SELECT statements joined by the UNION operator.
Syntax
[ FOR BROWSE ]

OPTION Clause
Specifies that the indicated query hint should be used throughout the entire query. Each query hint can be specified only once, although multiple query hints are permitted. The OPTION clause must be specified with the outermost query of the statement. The query hint affects all operators in the statement. If a UNION is involved in the main query, only the last query involving a UNION operator can have the OPTION clause. If one or more query hints causes the query optimizer to not generate a valid plan, SQL Server recompiles the query without the specified query hints, and issues a SQL Server Profiler event.

Caution Because the query optimizer usually selects the best execution plan for a query, it is recommended that , , and be used only as a last resort by experienced database administrators.

Syntax
[ OPTION ( [,...n) ]
::= { { HASH ORDER } GROUP { CONCAT HASH MERGE } UNION { LOOP MERGE HASH } JOIN FAST number_rows FORCE ORDER MAXDOP number ROBUST PLAN KEEP PLAN }
Arguments
{HASH ORDER} GROUP
Specifies that aggregations described in the GROUP BY or COMPUTE clause of the query should use hashing or ordering.
{MERGE HASH CONCAT} UNION
Specifies that all UNION operations are performed by merging, hashing, or concatenating UNION sets. If more than one UNION hint is specified, the optimizer selects the least expensive strategy from those hints specified.
{LOOP MERGE HASH } JOIN
Specifies that all join operations are performed by loop join, merge join, or hash join in the whole query. If more than one join hint is specified, the optimizer selects the least expensive join strategy for the allowed ones. If, in the same query, a join hint is also specified for a specific pair of tables, it takes precedence in the joining of the two tables.
FAST number_rows
Specifies that the query is optimized for fast retrieval of the first number_rows (a nonnegative integer). After the first number_rows are returned, the query continues execution and produces its full result set.
FORCE ORDER
Specifies that the join order indicated by the query syntax is preserved during query optimization.
MAXDOP number
Overrides the max degree of parallelism configuration option (of sp_configure) only for the query specifying this option. All semantic rules used with max degree of parallelism configuration option are applicable when using the MAXDOP query hint.
ROBUST PLAN
Forces the query optimizer to attempt a plan that works for the maximum potential row size, possibly at the expense of performance. When the query is processed, intermediate tables and operators may need to store and process rows that are wider than any of the input rows. The rows may be so wide that, in some cases, the particular operator cannot process the row. If this happens, SQL Server produces an error during query execution. By using ROBUST PLAN, you instruct the query optimizer not to consider any query plans that may encounter this problem.
KEEP PLAN
Forces the query optimizer to relax the estimated recompile threshold for a query. The estimated recompile threshold is the point at which a query is automatically recompiled when the estimated number of indexed column changes (update, delete or insert) have been made to a table. Specifying KEEP PLAN ensures that a query will not be recompiled as frequently when there are multiple updates to a table.
Remarks
The order of the clauses in the SELECT statement is significant. Any of the optional clauses can be omitted, but when used, they must appear in the appropriate order.
The length returned for text or ntext columns included in the select list defaults to the smallest of the actual size of the text, the default TEXTSIZE session setting, or the hard-coded application limit. To change the length of returned text for the session, use the SET statement. By default, the limit on the length of text data returned with a SELECT statement is 4,000 bytes.
SQL Server raises exception 511 and rolls back the current executing statement if either of these occur:
The SELECT statement produces a result row or an intermediate work table row exceeding 8,060 bytes.
The DELETE, INSERT, or UPDATE statement attempts action on a row exceeding 8,060 bytes.
In SQL Server, an error occurs if no column name is given to a column created by a SELECT INTO or CREATE VIEW statement.

Thursday, November 1, 2007

quick reference of paging

hi friends,

a quick reference of paging i found here :

http://4guysfromrolla.com/webtech/062899-1.shtml

CREATE PROCEDURE sp_PagedItems
(
@Page int,
@RecsPerPage int
)
AS

-- We don't want to return the # of rows inserted
-- into our temporary table, so turn NOCOUNT ON
SET NOCOUNT ON


--Create a temporary table
CREATE TABLE #TempItems
(
ID int IDENTITY,
OrderNo numeric(9)

)


-- Insert the rows from tblItems into the temp. table
INSERT INTO #TempItems (OrderNo)
SELECT OrderNo FROM OrderNo ORDER BY OrderNo

-- Find out the first and last record we want
DECLARE @FirstRec int, @LastRec int
SELECT @FirstRec = (@Page - 1) * @RecsPerPage
SELECT @LastRec = (@Page * @RecsPerPage + 1)

-- Now, return the set of paged records, plus, an indiciation of we
-- have more records or not!
SELECT *,
MoreRecords =
(
SELECT COUNT(*)
FROM #TempItems TI
WHERE TI.ID >= @LastRec
)
FROM #TempItems
WHERE ID > @FirstRec AND ID < @LastRec


-- Turn NOCOUNT back OFF
SET NOCOUNT OFF


GO