Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Converting Dynamic SQL to Parameterized Query

Author  Topic 

vijayan.vinu3
Starting Member

19 Posts

Posted - 2012-08-17 : 03:18:33
Hi

I have the following sample script which does a Dynamic Pivot on a table as follows:


--Creating Table

Create Table Ex
(InvoiceNumber int,
BillName Varchar(5) )


--Inserting Sample Data

Insert into Ex
Select 1, 'Amit'
Union ALL
Select 2, 'Amit'
Union ALL
Select 3, 'BBB'
Union ALL
Select 4, 'Amit'


--Dynamic Pivot

Declare @cols Varchar(max), @sql Varchar(max)
Select @cols = STUFF((Select ', [' + CAST(InvoiceNumber As Varchar(10) ) + ']' From Ex For XML Path('')), 1, 2, '')
Set @sql = 'Select '+@cols+' From Ex
Pivot
(MAX(BillName) For InvoiceNumber IN ('+@cols+') ) As pvt'
Execute (@sql)


I have done Parameterized queries where parameters are passed into the where clause. But, what I wanted to ask is if we can change this whole dynamic pivot into a Parameterized Query where parameters can be passed into the "Select" part of the query and then Executed using "sp_Executesql".

I have read quite a bit about Parameterized Queries on the internet but have only seen blog posts or explanations where Parameters are passed into the Where Clause of the Parameterized Query. Is it possible to Parameterize the "Select" or any other parts of the query??...

Any insight you might have on Parameterized queries would be really helpful. It would be even better if you could reccommend some good reads on this topic.

Looking forward to replies.

Vinu Vijayan

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2012-08-17 : 05:32:42
quote:

Any insight you might have on Parameterized queries would be really helpful. It would be even better if you could reccommend some good reads on this topic.


http://www.sommarskog.se/dynamic_sql.html

you can't parameterise anything except what would go into variables in standard sql

Transact Charlie
Msg 3903.. The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
http://nosqlsolution.blogspot.co.uk/
Go to Top of Page

vijayan.vinu3
Starting Member

19 Posts

Posted - 2012-08-17 : 07:23:02
Thanks for the link Charlie....seems like a good read. I'll try implementing into this scenario and get back to you with the results.
Go to Top of Page
   

- Advertisement -