can we use CASE with EXEC
Asked Answered
C

4

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?

Cabala answered 13/4, 2012 at 15:27 Comment(1)
CASE is used for inline evaluation within a query. You want IF since it's a flow control construct.Testa
T
13

You want to use the IF construct here:

IF @InputParam = 'XML'
    EXEC GetXMLData @ID, 'y'
IF @InputParam = 'TABLE'
    EXEC GetTableData @ID, 'y'
Testa answered 13/4, 2012 at 15:34 Comment(0)
T
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
Tiphany answered 13/4, 2012 at 15:29 Comment(0)
E
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
Erdei answered 13/4, 2012 at 15:29 Comment(3)
I think you mean to use IF instead of CASE here...This is invalid syntax.Testa
Yes @Testa is right, I had tried the above code earlier, and it had not worked.Cabala
@Cabala ok, you may use IF then. I was using Sybase-ASE syntax :PErdei
H
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)
Huxham answered 16/10, 2017 at 18:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.