Bonjour!
So, in a stored procedure I would like to do a conditional union decided by a parameter. How can I do that?
Here is my "doesn't work" procedure :
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spp_GetAdressesList]
@OnlyLinked bit = 1,
@ObligedId int = -1
AS
BEGIN
SELECT
[ID_ADRESS]
,[ID_ENT]
,[VOI_ADRESS]
,[NUM_ADRESS]
,[BTE_ADRESS]
,[CP_ADRESS]
,[VIL_ADRESS]
FROM [ADRESSES]
WHERE
(
(VIL_ADRESS != 'NC' AND VIL_ADRESS != '--')
AND
(@OnlyLinked = 0 OR ID_ENT is not null)
)
IF (@ObligedId != -1)
BEGIN
UNION
SELECT
[ID_ADRESS]
,[ID_ENT]
,[VOI_ADRESS]
,[NUM_ADRESS]
,[BTE_ADRESS]
,[CP_ADRESS]
,[VIL_ADRESS]
FROM [ADRESSES]
WHERE
ID_ADRESS = @ObligedId
END
END
So if @ObligedId est = a -1 I would like to doesn't have the UNION.
I made this with a dynamic varchar query, at the end I was executing the query with an exec. But it's apparently less efficient and you can make sql injection (It is for asp.net application) with dynamic queries. I decided to change all my stored procedures
It's not possible to do an union in a IF clause?
Thanks for all answers without exceptions..