We help IT Professionals succeed at work.
Get Started

DYNAMIC SQL

412 Views
Last Modified: 2012-05-09
My attached code works fine if I pass in a single id (1333)

However..the goal is to be able to pass in a single, a NULL (for all) or a means to do a where dealID IN (@dealID) for a group of id's.

Right now...
1333 returns the correct record
NULL retruns :
onversion failed when converting the varchar value 'NULL' to data type int.


And
DECLARE @dealID int
set @dealID = '1,2,3,4,5'
Returns:
Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the varchar value '1,2,3,4,5' to data type int.


use portal
go
DECLARE @dealID int
set @dealID = NULL
DECLARE @columns VARCHAR(max)  
SELECT @columns = COALESCE(@columns + ',', '') + '[' + eventType + ']'  
FROM CRMPROD_01.dbo.P_Events_Table_Types
DECLARE @query VARCHAR(max)  
  
SET @query = '  
SELECT *  
FROM (  
        select	pd.dealId, 
				pett.eventType, 
				pet.eventData  
			from		CRMPROD_01.dbo.P_Deals pd
			cross join	CRMPROD_01.dbo.P_Events_Table_Types pett
			left join	CRMPROD_01.dbo.P_Events_Table pet
						on pet.dealId = pd.dealId 
						and pet.eventTypeID = pett.eventTypeID  
			where pett.active = ''true'' and pd.dealID = ''' + ISNull(str(@dealID),'NULL') + ''' 
) Pv  
PIVOT  
(  
MAX(eventData)  
FOR [eventType]  
IN (' + @columns + ')  
)  
AS p'  
EXECUTE(@query)

Open in new window

Comment
Watch Question
CERTIFIED EXPERT
Expert of the Quarter 2010
Expert of the Year 2010
Commented:
This problem has been solved!
Unlock 2 Answers and 14 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE