9

I want to select a stored proc to execute based on user input. Something like -

EXEC
CASE @InputParam 
  WHEN 'XML' THEN GetXMLData @ID, 'y'
  WHEN 'TABLE' THEN GetTableData @ID, 'y'
END

Can this be done with CASE or should I consider using the If construct?

yoozer8
  • 7,361
  • 7
  • 58
  • 93
neuDev33
  • 1,573
  • 7
  • 41
  • 54
  • 2
    `CASE` is used for inline evaluation within a query. You want `IF` since it's a flow control construct. – JNK Apr 13 '12 at 15:35

4 Answers4

13

You want to use the IF construct here:

IF @InputParam = 'XML'
    EXEC GetXMLData @ID, 'y'
IF @InputParam = 'TABLE'
    EXEC GetTableData @ID, 'y'
JNK
  • 63,321
  • 15
  • 122
  • 138
3

In this scenario I think that even if SQL Server allowed that, an IF would be more clear.

IF @InputParam = 'XML'
BEGIN
    exec GetXMLData @ID, 'y'
END
ELSE IF @InputParam = 'TABLE'
BEGIN
    exec GetTableData @ID, 'y'
END
Jeremy Pridemore
  • 1,995
  • 1
  • 14
  • 24
1

You can do it like this:

IF @InputParam = 'XML'
BEGIN
   EXEC GetXMLData @ID, 'y'
END

IF @InputParam = 'TABLE'
BEGIN
   EXEC GetTableData @ID, 'y'
END
aF.
  • 64,980
  • 43
  • 135
  • 198
1

You could use CASE, but you'll have to use EXEC (cmd):

DECLARE 
@cmd VARCHAR(200)
, @InputParam VARCHAR(5) ='TABLE'
, @ID INT =1

SELECT @cmd = ( CASE @InputParam 
WHEN 'XML' THEN 'GetXMLData '
      +CONVERT(VARCHAR,@ID)+', '+CHAR(39)+'y'+CHAR(39)
WHEN 'TABLE' THEN 'GetTableData '
      +CONVERT(VARCHAR,@ID)+', '+CHAR(39)+'y'+CHAR(39)
END)
EXEC(@cmd)
Vonpato
  • 41
  • 2