Posts

Showing posts from 2008

Execute Dynamic SQL commands in SQL Server

In some applications having hard-coded SQL statements is not appealing, because of the dynamic nature of the queries being issued against the database server. Because of this sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can be done quite simply from the application perspective where the statement is built on the fly whether you are using ASP.NET , ColdFusion or any other programming language. But how do you do this from within a SQL Server stored procedure? SQL Server offers a few ways of running a dynamically built SQL statement. These ways are: Writing a query with parameters Using EXEC Using sp_executesql Writing a query with parameters This first approach is pretty straightforward if you only need to pass parameters into the WHERE clause of your SQL statement. Let’s say we need to find all records from the Customers table where City = ‘London’. This can be done easily as the following example shows.

How To search entire database?

While browsing the SQL Server newsgroups, there are occasional requests for a script capable of searching all the columns of all the tables in a given database for a specific keyword. Although it might seem trivial, the need for such a script became apparent in a real-world scenario. In troubleshooting a problem with Microsoft Operations Manager (MOM), which utilizes SQL Server for storing computer, alert, and performance-related information, a network administrator needed to search all the MOM tables for a specific string. Lacking a readily available script, manual searching ensued. This experience prompted the creation of a stored procedure called “SearchAllTables.” SearchAllTables Stored Procedure The SearchAllTables stored procedure takes a search string as an input parameter and systematically searches all char , varchar , nchar , and nvarchar columns of all tables (excluding system tables) owned by all users in the current database. Feel free to extend this procedure to sea

Turning Tables into Delimited Text

Creating a Comma-Separated List of Authors for a Title in SQL Server In certain scenarios, representing data in a relational format might not be the most intuitive choice. For instance, when dealing with lists associated with rows, displaying them as comma-separated text can be more practical, especially for reports and online grids. In this blog post, I’ll share a scalar user-defined function (UDF) that implements this technique. The udf_Titles_AuthorList Function CREATE FUNCTION udf_Titles_AuthorList ( @title_id char ( 6 ) -- title ID from pubs database ) RETURNS varchar ( 255 ) -- List of authors -- No SCHEMABINDING reads data from another DB /* * Returns a comma-separated list of the last name of all * authors for a title. * * Example: * Select Title, dbo.udf_Titles_AuthorList(title_id) as [Authors] * FROM pubs..titles ORDER by Title ****************************************************************/ AS BEGIN DECLARE @lname varchar

How to rename a Stored Procedure in SQL

Sometimes by mistake, if you create a wrongly named stored procedure, you can easily rename the store procedure. Checkout following commands for renaming the stored procedure Syntax: sp_rename 'procedure_name1' , 'procedure_name2' procedure_name1 The current name of the stored procedure procedure_name2 The new name of the stored procedure. A stored procedure can be renamed. The new name should follow the rules for identifiers. Examples ` EXEC sp_rename 'spGetAvgGrade' , 'spNewAvgGrade' ; ` Output: Caution: Changing any part of an object name could break scripts and stored procedures. The object was renamed to ‘spNewAvgGrade’.` Explanation: In the above example, we change the name of the stored procedure spGetAvgGrade to spNewAvgGrade.

Implementing Custom Paging in ASP.NET with SQL Server 2005

Why Custom Paging? Custom paging allows you to get a limited number of records from a large database table that saves processing time of your database server as well as your application server and makes your application scalable, efficient and fast. In this article, I am going to explain how to create a stored procedure in SQL Server 2005 that allows you to pass startRowIndex and pageSize as a parameter and return you the number of records starting from that row index to the page size specified. It was possible in the SQL Server 2000 too but it was not as easy as in SQL Server 2005 is. -- EXEC LoadPagedArticles 10, 5 Let’s create the function CREATE PROCEDURE LoadPagedArticles -- Add the parameters for the stored procedure here @startRowIndex int , @pageSize int AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON ; -- increase the startRowIndex by 1 to avoid returning the last record ag

Execute Dynamic SQL commands in SQL Server

In some applications having hard coded SQL statements is not appealing, because of the dynamic nature of the queries being issued against the database server. Because of this sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can be done quite simply from the application perspective where the statement is built on the fly whether you are using ASP.NET , ColdFusion or any other programming language. But how do you do this from within a SQL Server stored procedure? SQL Server offers a few ways of running a dynamically built SQL statement. These ways are: Writing a query with parameters Using EXEC Using sp_executesql Writing a query with parameters This first approach is pretty straight forward if you only need to pass parameters into your WHERE clause of your SQL statement. Let’s say we need to find all records from the customers table where City = ‘London’. This can be done easily such as the following example s

Every SQL developer must know about sql case command

suppose We need a stored procedure that can be called by an application but the user wants to be able to sort by either first name or last name. One would be tempted to use dynamic SQL to solve this problem, but we can use CASE to create a dynamic SQL equivalent CREATE PROCEDURE dbo . getCustomerData @sortby VARCHAR ( 9 ) , @sortdirection CHAR ( 4 ) AS SET nocount ON SELECT customerid , firstname , lastname , statecode , statedescription , totalsales FROM dbo . Customer ORDER BY CASE @sortdirection WHEN 'asc' THEN CASE @sortby WHEN 'firstname' THEN firstname WHEN 'lastname' THEN lastname END END ASC , CASE @sortdirection WHEN 'desc' THEN CASE @sortby WHEN 'firstname' THEN firstname WHEN 'lastname' THEN lastname END END DESC GO How to execute EXEC dbo . getCustomerData 'lastname' , 'desc' A final requirement has crossed our desk

Convert Table To Pivot Table Using SQL Coalesce Operator

Using Coalesce to Pivot If you run the following statement against the AdventureWorks database, SELECT Name FROM HumanResources . Department WHERE ( GroupName = 'Executive General and Administration' ) you will come up with an expected result. You could run the following command if you want to pivot the data. DECLARE @DepartmentName VARCHAR ( 1000 ) SELECT @DepartmentName = COALESCE ( @DepartmentName , '' ) + Name + ',' FROM HumanResources . Department WHERE ( GroupName = 'Executive General and Administration' ) SELECT @DepartmentName AS DepartmentNames And get the result set with comma-separated in a single column.

SQL Server Function to Determine a Leap Year

The following scalar function takes in a year and returns a bit flag indicating whether the passing year is a leap year or not. create function dbo . fn_IsLeapYear ( @year int ) returns bit as begin return ( select case datepart ( mm , dateadd ( dd , 1 , cast ( ( cast ( @year as varchar ( 4 ) ) + '0228' ) as datetime ) ) ) when 2 then 1 else 0 end ) end go That’s all there is to it! The function takes in the year, appends ‘0228’ to it (for February 28th) and adds a day. If the month of the next day is a 2 (as extracted by the DATEPART function), then we’re still in February, so it must be a leap year! If not, it is not a leap year. Here are a few examples: select dbo . fn_IsLeapYear ( 1900 ) as 'IsLeapYear?' select dbo . fn_IsLeapYear ( 2000 ) as 'IsLeapYear?' select dbo . fn_IsLeapYear ( 2007 ) as 'IsLeapYear?' select dbo . fn_IsLeapYear ( 2008 ) as 'IsLeapYear?'

Convert Row to column as csv in sql

Raw Data: id name services 1 Joe AA 1 Joe AB 1 Joe AC 2 Judy GH 2 Judy GC 3 Kevin AA 3 Kevin GH Result Set: id name services 1 Joe AA, AB, AC 2 Judy GH, GC 3 Kevin AA, GH If you have MSSQL2K, then the most performant (and arguably most elegant) way woud be to use a user - defined function : Let’s prepare some sample data create table t1 ( id int , name varchar ( 10 ) , services varchar ( 10 ) ) insert into t1 values ( 1 , 'Joe' , 'AA' ) insert into t1 values ( 1 , 'Joe' , 'AB' ) insert into t1 values ( 1 , 'Joe' , 'AC' ) insert into t1 values ( 2 , 'Judy' , 'GH' ) insert into t1 values ( 2 , 'Judy' , 'GC' ) insert into t1 values ( 3 , 'Kevin' , 'AA' ) insert into t1 values ( 3 , 'Kevin' , 'GH' ) Now let’s create a function named my_comma_sep, as shown below create function my_comma_sep ( @id int )

How to handle CSV as input in sql stored procedure

CREATE PROCEDURE dbo . sp1 @list as varchar ( 200 ) AS exec ( 'SELECT field1, field2, field3 FROM Table1 WHERE UPPER(RIGHT(RTRIM(field1),3)) IN ( ' + @list + ' ) ' ) and you need to call this proc as below exec sp1 @list = '' 'DFG' ',' 'ABC' ',' 'ASD' ',' 'FGH' ''

How to implement UPSERT in SQL

CREATE PROCEDURE dbo . spAddUserName ( @UserID AS int , @FirstName AS varchar ( 50 ) , @LastName AS varchar ( 50 ) ) AS BEGIN DECLARE @rc int UPDATE [ Users ] SET FirstName = @FirstName , LastName = @LastName WHERE UserID = @UserID /* how many rows were affected? */ SELECT @rc = @ @ROWCOUNT IF @rc = 0 BEGIN INSERT INTO [ Users ] ( FirstName , LastName ) VALUES ( @FirstName , LastName ) END END

What is Best Way TO Count Number Of Rows

select rows from sysindexes where id = OBJECT_ID ( @table_name ) and indid < 2
dbcc checkident ( TableName, reseed, 0 )

Row To Column

Suppose you have a table structure like create table tmpStocks ( [StockSymbol] [char] (8), [ExchMM] [varchar] (10) ) go create table tmpExchanges ( [Name] [char] (10), [ExchSymbo] [char] (1) ) go 2. Insert some values: insert into tmpStocks (stocksymbol,exchmm) values ('KS','IP') insert into tmpStocks (stocksymbol,exchmm) values ('PK6','IB') insert into tmpStocks (stocksymbol,exchmm) values ('LHJ','I') insert into tmpStocks (stocksymbol,exchmm) values ('JHL','P') insert into tmpExchanges (name,ExchSymbo) values ('ISE','I') insert into tmpExchanges (name,ExchSymbo) values ('BOX','B') insert into tmpExchanges (name,ExchSymbo) values ('PCost','P') and you want result like how to get the results as following: [StockSymbol] [ExchMM] [ISE] [BOX] [PCost] ks IP 1 0 1 PK6

Covert Row To Column In SQL Server 2005

Let us suppose that you have a table like below col1 | col2 | col3 --------*---------*---------- Value 1 | Value 2 | Value 3 And change it to one that looks like this: Name | Value -----*--------- col1 | Value 1 -----*--------- col2 | Value 2 -----*--------- col3 | Value 3 DECLARE @ Table Table (col1 varchar (10), col2 varchar (10), col3 varchar (10)) INSERT INTO @ TABLE VALUES ( 'Value 1' , 'Value 2' , 'Value 3' ) INSERT INTO @ TABLE VALUES ( 'Value 4' , 'Value 5' , 'Value 6' ) INSERT INTO @ TABLE VALUES ( 'Value 7' , 'Value 8' , 'Value 9' ) SELECT col, colval FROM ( SELECT col1, col2, col3 FROM @ TABLE ) p UNPIVOT (ColVal FOR Col IN (col1, col2, col3) ) AS unpvt

Sorting IP Addresses in SQL

IP addresses are represented in dotted-decimal notation, i.e. four numbers, each ranging from 0 to 255 and separated by dots. Each range from 0 to 255 can be represented by 8 bits and is thus called an octet. Some first octet values like 127 have special meaning - 127 means the local computer. Octets 0 and 255 are not acceptable values in some situations. 0 can, however, be used as the second and third octet. So, as you can imagine, unless we store the data in a sortable friendly way, sorting this data would require some string manipulation. Let’s follow this up with an example: CREATE TABLE IP_ADDR ( COL1 NVARCHAR ( 30 ) ) ; INSERT INTO IP_ADDR VALUES ( ‘ 30.33 . 33.30 ′ ) ; INSERT INTO IP_ADDR VALUES ( ‘ 256.10 . 1.2 ′ ) ; INSERT INTO IP_ADDR VALUES ( ‘ 256.255 . 10.2 ′ ) ; INSERT INTO IP_ADDR VALUES ( ‘ 127.0 . 0.1 ′ ) ; INSERT INTO IP_ADDR VALUES ( ‘ 132.22 . 33.44 ′ ) ; INSERT INTO IP_ADDR VALUES ( ‘ 132.10 . 30.1 ′ ) ; INSERT INTO IP_ADDR

How To Sort DateField(where datafield is stored as varchar)

9101,,3/28/2008,~/images/PlusSign.gif,~/images/PlusSign.gif,~/images/PlusSign.gif,~/images/PlusSign.gif,1,400 9102,,3/7/2008,~/images/PlusSign.gif,~/images/PlusSign.gif,~/images/PlusSign.gif,~/images/PlusSign.gif,1,400 9103,~/images/PlusSign.gif,~/images/PlusSign.gif,~/images/PlusSign.gif,~/images/PlusSign.gif,~/images/PlusSign.gif set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go ALTER proc [dbo].[usp_getsevent] @userid int as create table #tempdat (scheduleeventid int, eventdate varchar(100),opponents varchar(100),locationname varchar(100),eventtime varchar(100),officials varchar(100)) create table #tempdat1 (scheduleeventid int, eventdate varchar(100),opponents varchar(100),locationname varchar(100),eventtime varchar(100),officials varchar(100)) create table #tempdat2 (scheduleeventid int, eventdate varchar(100),opponents varchar(100),locationname varchar (100),eventtime varchar(100),officials varchar(100)) declare @scheduleeventid int, @eventdate varchar(100),@opponents

Setting the execution order of Triggers in SQL Server

Using sp_Settriggerorder stored procedure, we can define the execution order of the trigger. Here is the syntax for SQL Server 2005, taken from BOL. For complete explanation of syntax, please look at BOL. sp_settriggerorder [ @triggername = ] ‘[ triggerschema. ] triggername’ , [ @order = ] ‘value’ , [ @stmttype = ] ’statement_type’ [ , [ @namespace = ] { ‘DATABASE’ | ‘SERVER’ | NULL } ] We are interested in the second parameter: “order”. It can take three values which means that it can take into account up-to three triggers. First – Trigger is fired first Last - Trigger is fired last None – Trigger is fired in random order. The same procedure is available in SQLServer 2000 also but without namespace parameter because it does not support DDL triggers. Since SQL Server 2005, supports DDL trigger, namespace parameter defines the scope of the DDL trigger whether at Database level or at Server level. If value is NULL, trigger is a DML trigger. We will use the same example as shown in

Update data in one table with data from another table

Updating Multiple Columns in a Table Using Values from Another Table - A Cross-Platform Approach In relational database management systems (RDBMS), updating multiple columns in one table with values from another is a common task. Let’s explore how to achieve this in three widely-used systems: SQL Server, MySQL, and PostgreSQL. For this demonstration, we have two tables, TableA and TableB, linked by a foreign key relationship. Table Structures and Data TableA: a b c d 1 x y z 2 a b c 3 t x z TableB: a1 b1 c1 d1 e1 1 x1 y1 z1 40 2 a1 b1 c1 50 The goal is to update columns b, c, and d in TableA from the corresponding columns in TableB, based on the foreign key relationship (TableA.a = TableB.a1) and an additional condition (TableB.e1 > 40). SQL Server UPDATE TABLEA SET b = TABLEB .b1 , c = TABLEB .c1 , d = TABLEB .d1 FROM TABLEA INNER JOIN TABLEB ON TABLEA .a = TABLEB .a1 WHERE TABLEB .e1 > 40 ;

Functional difference between “NOT IN” vs “NOT EXISTS” clauses

Image
“NOT IN” and “NOT EXISTS” clauses are not the same functionally or performance wise and, therefore, should be used appropriately. This blog post outlines how these commands are executed and discusses when it is appropriate to use them. Sample data: /******************************************************************************************* Create a dummy EMP_MASTER table populate it with some records for illustration. This is Oracle Syntax. There are ten employees that have been created and 9 out of those 10 report to their manager: Dennis who is at the head of the chain and does not have a manager to report to. ********************************************************************************************/ CREATE TABLE EMP_MASTER ( EMP_NBR NUMBER(10) NOT NULL PRIMARY KEY, EMP_NAME VARCHAR2(20 CHAR), MGR_NBR NUMBER(10) NULL ) / INSERT INTO EMP_MASTER VALUES (1, ‘DON’, 5); INSERT INTO EMP_MASTER VALUES (2, ‘HARI’, 5); INSERT INTO EMP_MASTER VALUES (3, ‘RAMESH’, 5); INSERT INTO EMP_MA

Multiple NULL values in a Unique index in SQL

this project needed to support having multiple NULL values in the column and still have a UNIQUE constraint . That is allowed by Oracle but not in SQL Server and DB2 LUW. There is a way to make this work in SQL Server and DB2 LUW also but that requires a work -around. Consider this table : CREATE TABLE TEST_UQ (COL1 INT IDENTITY (1,1) PRIMARY KEY , COL2 NVARCHAR(10) NULL ) GO In this table , COL1 has been declared as the primary key but we want a UNIQUE constraint to be put on COL2 as well. Please note that COL2 is a nullable column and that SQL Server does not allow multiple NULL values in a UNIQUE index and treats them the same way. We can test it out prior to proceeding with the work -around: Let tus create a unique index first : CREATE UNIQUE INDEX TEST_UQ_IND_1 ON TEST_UQ (COL2) GO Now, let us try to insert these values : insert into test_uq (col2) values (’abc’); insert into test_uq (col2) values (’xyz’); insert into

Using Index

select * from ZIPCodes where StateName = ‘ New York’ – Create Index create nonclustered index idxStateName on ZIPCodes(StateName) create nonclustered index idxZIPType on ZIPCodes(ZIPType) – Use Index select * from ZIPCodes with ( INDEX (idxZIPType)) where ZIPType = ‘S’ – List of Indexes on Perticular Table exec sp_helpindex ‘ps_client_master’ – Drop Index drop index ps_client_master.ps_client_master_Index_1