CREATE TABLE bit13
(
ID INT IDENTITY(1, 1) PRIMARY KEY,
campo_pk VARCHAR(100)
)
DECLARE @campo_pk VARCHAR(100),
@campo_pk2 VARCHAR(100),
@campo_pk3 VARCHAR(100)
SET @campo_pk = (SELECT campo_pk FROM bit13 WHERE ID = 1)
SET @campo_pk2 = (SELECT campo_pk FROM bit13 WHERE ID = 2)
SET @campo_pk3 = (SELECT campo_pk FROM bit13 WHERE ID = 3)
DECLARE @SQL NVARCHAR(100)
SET @SQL = (select count(*) from bit13)
EXEC('
IF ('+@SQL+' = 2)
BEGIN
IF (SELECT COUNT(*) FROM bit13 WHERE ID = 2) > 0
BEGIN
SELECT '+@campo_pk2+' FROM exp10
END
END
IF ('+@SQL+' = 3)
BEGIN
IF (SELECT COUNT(*) FROM bit13 WHERE ID = 2) > 0
BEGIN
SELECT '+@campo_pk2+' FROM exp10
END
IF (SELECT COUNT(*) FROM bit13 WHERE ID = 3) > 0
BEGIN
SELECT '+@campo_pk3+' FROM exp10
END
END
')
I have the following problem, I try to generate a bitacora by means of triggers, I have several tables with primary keys composed, so, in table bit13 I store the primary keys of a table, my tables can have up to 5 or 6 primary keys . @sql contains the number of primary keys Let's suppose that I bring 3 primary keys according to the code inside the exec (field_pk, field_pk2, field_pk3), so what happens if I decide to take a table of two primary keys having my code in case they are 2 and 3 primary keys.
If @sql is 2, then ask me the value of field_pk2 only If @sql is 3, then ask me the value of field_pk2 and field_pk3 only.
in this case, @sql is 2, and therefore you should only bring me campo_pk2, in this case, there are two conditions @sql = 2 and @sql = 3, because if @sql = 2 go to @sql = 3 and it marks me an error
Msg 156, Level 15, State 1, Line 17 Incorrect syntax near the keyword 'FROM'.
I understand that bit13 does not contain the field_pk3 so it should mark error, but comment that last line
IF (SELECT COUNT(*) FROM bit13 WHERE ID = 3) > 0
BEGIN
SELECT '+@campo_pk3+' FROM exp10
END
and it does not show me any error.
I do not know if you explain me well, someone who can help me?
Thanks greetings!.