[SQL SERVER 2005][PRO STOCK] len(@monvarchar) incorrect
Bonjour,
Voilà je ne comprends pas j'ai un problème avec la procédure suivante :
A partir du 5eme n-uplet retourné par le curseur, le len(@SQL) n'est plus supérieur à 0 et je n'ai donc plus de ' UNION '
J'ai donc adapté mon code pour l'exemple et l'architecture ne peut pas etre changée (mais ce ne sont pas des magasins et des produits :))
Comment cela se fait-il qu'au bout de plusieurs boucles de mon curseur, la longeur de @SQl n'est plus correcte?
Merci d'avance car là je sèche vraiment à piger...
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
CREATE PROCEDURE [dbo].[procedure_test](
@id_magasin int = -1,
@prefixe_table nvarchar(100) = null
)
AS
DECLARE @SQL nvarchar(4000)
IF @id_magasin = -1
BEGIN
DECLARE C_MAGASIN CURSOR
FOR SELECT IDMAGASIN,nom,prefixe_table from vue_magasins_actifs
OPEN C_MAGASIN
DECLARE @IDMAGASIN INT
DECLARE @nom nvarchar(100)
DECLARE @prefixe_table nvarchar(50)
SET @SQL = ''
SET@IDMAGASIN = 0
SET @nom = ''
SET @prefixe_table = ''
FETCH C_MAGASIN INTO @IDMAGASIN,@nom,@prefixe_table
WHILE @@FETCH_STATUS = 0
BEGIN
IF len(@SQL) >0
BEGIN
SET @SQL = @SQL + ' UNION '
PRINT ' UNION ' + ''
END
ELSE
BEGIN
PRINT ' SQL = /'
END
SET @SQL = @SQL + '(Select * from ' + @prefixe_table + 'produits where en_promo= 1 )'
PRINT '(Select * from ' + @prefixe_table + 'produits where en_promo= 1 )'
FETCH C_MAGASIN INTO @IDMAGASIN,@nom,@prefixe_table
END
CLOSE C_MAGASIN
DEALLOCATE C_MAGASIN
exec sp_executesql @SQL
--print @SQL
END
ELSE
BEGIN
SET @SQL ='Select * from ' + @prefixe_table1 + 'produits where en_promo= 1'
print 'Select * from ' + @prefixe_table1 + 'produits where en_promo= 1'
IF len(@SQL)>0
BEGIN
exec sp_executesql @SQL
END
END |
et le résultat retourné
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| (Select * from mag1_produits where en_promo=1)
UNION
(Select * from mag2_produits where en_promo=1)
UNION
(Select * from mag3_produits where en_promo=1)
UNION
(Select * from mag4_produits where en_promo=1)
UNION
(Select * from mag5_produits where en_promo=1)
(Select * from mag6_produits where en_promo=1)
(Select * from mag7_produits where en_promo=1) |