Reputation: 27
The code below tries to use case condition to create a table or another. What would be the sql way to express that?
DECLARE @tmp VARCHAR(255)
SET @tmp = 'A'
SELECT CASE @tmp
WHEN 'A' THEN CREATE TABLE #Hello (ID Int, Hello varchar)
WHEN 'B' THEN CREATE TABLE #Goodbye (ID Int, Goodby varchar)
END
Upvotes: 0
Views: 527
Reputation: 4039
Instead of a CASE statement, simply use IF, since inside the CASE
statement you cannot control the flow of execution of TSQL Statements or use DDL statements.
As per @ Zohar Peled's comment, I am adding an arbitrary length to the varchar
fields, since they had been declared without any:
DECLARE @tmp VARCHAR(255)
SET @tmp = 'A'
IF @tmp = 'A'
BEGIN
--PRINT 'Creating table #Hello'
CREATE TABLE #Hello (ID Int, Hello varchar(128))
END
ELSE
IF @tmp = 'B'
BEGIN
--PRINT 'Creating table #Goodbye'
CREATE TABLE #Goodbye (ID Int, Goodby varchar(128))
END
Upvotes: 3