Posts

Showing posts from April, 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 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