I suggest two ways of doing:
Form 1 - Condition in select
In this case your Index will always be declared with all fields, and instead of values, you will use a conditioned query.
DECLARE @opcao VARCHAR(10) = 'opcao3'
INSERT INTO TABELA (ID, CAMPO1, CAMPO2, CAMPO3)
SELECT 11, CASE @opcao WHEN 'opcao1' THEN 20 ELSE NULL END 'Campo1'
, CASE @opcao WHEN 'opcao2' THEN 20 ELSE NULL END 'Campo2'
, CASE @opcao WHEN 'opcao3' THEN 20 ELSE NULL END 'Campo3'
Form 2 - Running a custom query
Compatibilities
The execute
is available in SQL Server 2008 onwards.
On the Oracle, we have the command execute immediate
, available from 10g Release 2 (10.2).
Already in this form, you will need to mount a string with your query by mounting the Insert exactly as you need it.
DECLARE @opcao VARCHAR(10) = 'opcao3'
DECLARE @cmd VARCHAR(MAX)
SET @cmd = 'INSERT INTO TABELA (ID, '+ CASE @opcao
WHEN 'opcao1' THEN 'campo1'
WHEN 'opcao2' THEN 'campo2'
ELSE 'campo3'
END +')'+
' VALUES (''11'', ''20'')'
EXECUTE(@cmd)
What result? Can you explain the doubt better? Welcome to Stackoverflow, I recommend reading on tour to understand a little more about the operation of the site.
– Marconi
That sounds like a hell of a gambiarra =]
– Rovann Linhalis
Hello, my suggestion is to make this logic in the code.
– Pedro Henrique
Which SQL engine?
– bfavaretto
Try to explain why you’re doing this, you might have other ideas.
– Dudaskank