Question

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?

Was it helpful?

Solution

You want to use the IF construct here:

IF @InputParam = 'XML'
    EXEC GetXMLData @ID, 'y'
IF @InputParam = 'TABLE'
    EXEC GetTableData @ID, 'y'

OTHER TIPS

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

You can do it like this:

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

IF @InputParam = 'TABLE'
BEGIN
   EXEC GetTableData @ID, 'y'
END

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top