Posts

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