Friday, March 18, 2005

Building SQL Strings

Here is a nice utility to make sql strings from the Query which you have created. To do this create the following procedure in your master database

CREATE PROCEDURE sp_SqlForCS
@Sql varchar(4000)
AS
SET NoCount On
-- Never change this
SELECT '
StringBuilder Sql = new StringBuilder();

Sql.Append("'
+ replace(
-- Never change this
replace(replace(replace(replace(@Sql,'SELECT','SELECT'),'FROM','FROM'),'WHERE','WHERE'),'INNER JOIN','INNER JOIN')

-- Never change this
,
'

',
'");
Sql.Append("')+ '");'

-- Never change this
SET NoCount Off


Now you can start preparing your sql statement from Query analyzer. Once you have done with the formatting and the rest of the stuff, put a single quote ['] before and after the query and execute sp_SqlForCS with the string as the paramter

sp_SqlForCS
'SELECT titles.title, titleauthor.au_ord, authors.au_lname, titles.price, titles.ytd_sales,
titles.pub_id
FROM authors
INNER JOIN titleauthor
ON authors.au_id = titleauthor.au_id
INNER JOIN titles
ON titleauthor.title_id = titles.title_id'


and you will get the following output

StringBuilder Sql = new StringBuilder();

Sql.Append("SELECT titles.title, titleauthor.au_ord, authors.au_lname, titles.price, ");
Sql.Append(" titles.ytd_sales, titles.pub_id");
Sql.Append("FROM authors ");
Sql.Append(" INNER JOIN titleauthor ");
Sql.Append(" ON authors.au_id = titleauthor.au_id ");
Sql.Append(" INNER JOIN titles ");
Sql.Append(" ON titleauthor.title_id = titles.title_id");

0 Comments:

Post a Comment

<< Home