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 do you delete duplicates rows from a table

1. copy the structure of base_temp into temp_table

select * into temp_table from base_temp where 1=0
2. create a unique index on the columns that contains the duplicate rows with the ignore_dup_key attribute .this may be more columns the key for the table.

Create unique index temp_idx on temp_table(col1,col2…..) with igmore_dup_key
3. Now insert base_table into temp_table
Insert temp_table select * from base_table
Truncate the base table and copy the data in temp_table to base_table

Comments

NITESH KAPOOR said…
Replace the keyword igmore_dup_key with ignore_dup_key than it works fine.
Ramesh Rathod said…
For Delete duplicate row
(Step - 1) SET ROWCOUNT 1 --(row count -1)
(Step - 2) DELETE FROM Tablename and your condition
Narasimha said…
This link provides different methods of deleting the duplicate rows

http://www.besttechtools.com/SQLArticles.aspx?ID=DeleteDuplicate

Popular posts from this blog

Check If Temporary Table Exists

Multiple NULL values in a Unique index in SQL

Row To Column