Blog de Laurent Valente

Responsable technique Microsoft , Akka technologies

Laurent Valente

moi

Consulatnt technique, Expert Microsoft chez AKKA Technologie.

J'accompagne les équipes sur les différents projets Microsoft.

Ma carte de visite Microsoft

Mon CV

Mon transcript

[SQL Server] Utilisation de cursor

Je suis sous SQL 2005 donc je n’ai pas accès à la commande MERGE qui fait l’objet d’un autre article sur ce blog (autrement dit si vous avez SQL 2008c’est exemple est plus optimisé d’autre l’article sur le MERGE)

L’idée est la suivante : j’ai une table stock qui contient des produits et leur quantité, par ailleurs j’ai une  table livraison qui contient des produits et leur quantité ce qui correspond au contenu du camion (oui Robert il est beau ton camion).

Quand il y a des produits dans le camion de Robert qui existe déjà dans mon stock, je veux que les quantités s’ajoutent. Quand il y a des produits en livraison que je n’ai pas en stock je veux créer une nouvelle ligne dans ma table stock.

Voici le script de création des deux tables :

USE [Base_stock]

 

GO

 

CREATE TABLE [dbo].[Table_Livraison](

 

      [Id_Livraison] [int] IDENTITY(1,1) NOT NULL,

 

      [id_Produit_Livraison] [int] NULL,

 

      [Produit_Livraison] [varchar](50) NULL,

 

      [quantite_Livraison] [int] NULL,

 

 CONSTRAINT [PK_Table_Livraison] PRIMARY KEY CLUSTERED

 

(

 

      [Id_Livraison] ASC

 

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

 

) ON [PRIMARY]

 

GO

 

CREATE TABLE [dbo].[Table_Stock](

 

      [Id_Stock] [int] IDENTITY(1,1) NOT NULL,

 

      [Id_Produit_Stock] [int] NULL,

 

      [Produit_Stock] [varchar](50) NULL,

 

      [Quantite_Stock] [int] NULL,

 

 CONSTRAINT [PK_Table_Stock] PRIMARY KEY CLUSTERED

 

(

 

      [Id_Stock] ASC

 

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

 

) ON [PRIMARY]

 

GO

 

Ensuite je vais mettre quelques données dans mes deux tables pour la démo.

use Base_stock

 

GO

 

INSERT INTO [Base_stock].[dbo].[Table_Stock]

 

           ([Id_Produit_Stock]

 

           ,[Produit_Stock]

 

           ,[Quantite_Stock])

 

     VALUES (1,'nutella',10)

 

    

 

INSERT INTO [Base_stock].[dbo].[Table_Stock]

 

           ([Id_Produit_Stock]

 

           ,[Produit_Stock]

 

           ,[Quantite_Stock])

 

     VALUES (5,'compote',20)

 

    

 

INSERT INTO [Base_stock].[dbo].[Table_Stock]

 

           ([Id_Produit_Stock]

 

           ,[Produit_Stock]

 

           ,[Quantite_Stock])

 

     VALUES(6,'brocolis',50)

 

    

 

INSERT INTO [Base_stock].[dbo].[Table_Stock]

 

           ([Id_Produit_Stock]

 

           ,[Produit_Stock]

 

           ,[Quantite_Stock])

 

     VALUES (7,'pommes',30)

 

    

 

INSERT INTO [Base_stock].[dbo].[Table_Stock]

 

           ([Id_Produit_Stock]

 

           ,[Produit_Stock]

 

           ,[Quantite_Stock])

 

     VALUES(8,'coca',40)

 

GO

 

INSERT INTO [Base_stock].[dbo].[Table_Livraison]

 

           ([id_Produit_Livraison]

 

           ,[Produit_Livraison]

 

           ,[quantite_Livraison])

 

     VALUES

 

           (2,'biere',10)

 

          

 

INSERT INTO [Base_stock].[dbo].[Table_Livraison]

 

           ([id_Produit_Livraison]

 

           ,[Produit_Livraison]

 

           ,[quantite_Livraison])

 

     VALUES(3,'tomates',200)

 

          

 

INSERT INTO [Base_stock].[dbo].[Table_Livraison]

 

           ([id_Produit_Livraison]

 

           ,[Produit_Livraison]

 

           ,[quantite_Livraison])

 

     VALUES(5,'compote',10)

 

          

 

INSERT INTO [Base_stock].[dbo].[Table_Livraison]

 

           ([id_Produit_Livraison]

 

           ,[Produit_Livraison]

 

           ,[quantite_Livraison])

 

     VALUES(1,'nutella',30)

 

         

 

INSERT INTO [Base_stock].[dbo].[Table_Livraison]

 

           ([id_Produit_Livraison]

 

           ,[Produit_Livraison]

 

           ,[quantite_Livraison])

 

     VALUES (9,'beurre',10)

 

          

 

GO

 

Donc pour récapituler voici le contenu de mes 2 tables.

result1

Bien, maintenant la mise en place du CURSOR voici le script après on en parle

declare @Id_Produit_Livraison  int

 

declare @Produit_Livraison  varchar(50)

 

declare @Quantite_Livraison  int

 

declare @maquantite_en_stock int

 

     

 

declare curseur_Livraison CURSOR for

 

      select Id_Produit_Livraison ,Produit_Livraison  ,Quantite_Livraison  from dbo.Table_Livraison

 

open curseur_Livraison

 

      fetch next from curseur_Livraison  into @Id_Produit_Livraison  ,@Produit_Livraison  ,@Quantite_Livraison

 

while @@FETCH_STATUS=0

 

Begin

 

      set @maquantite_en_stock=(select isnull(Quantite_stock,0) from dbo.Table_stock where Id_Produit_stock=@Id_Produit_Livraison)

 

      if @maquantite_en_stock<>0

 

      begin

 

            print 'update'

 

            update dbo.Table_stock  set Quantite_stock=Quantite_stock+@Quantite_Livraison where Id_Produit_stock=@Id_Produit_Livraison

 

      end

 

      else

 

      begin

 

            print 'insert'

 

            insert dbo.Table_stock values (@Id_Produit_Livraison,@Produit_Livraison,@Quantite_Livraison)

 

      end

 

           

 

fetch next from curseur_Livraison  into @Id_Produit_Livraison  ,@Produit_Livraison  ,@Quantite_Livraison

 

End

 

close curseur_Livraison

 

deallocate curseur_Livraison

 

Je commence par déclarer les variables dont j’aurais besoin :

 

declare @Id_Produit_Livraison  int

 

declare @Produit_Livraison  varchar(50)

 

declare @Quantite_Livraison  int

 

declare @maquantite_en_stock int

 

Ensuite je déclare un curseur et je l’associe à une commande select dont le nom des colonnes ressemble étrangement aux noms de mes variables…

 

declare curseur_Livraison CURSOR for

 

      select Id_Produit_Livraison ,Produit_Livraison  ,Quantite_Livraison  from dbo.Table_Livraison

 

J’ouvre mon curseur (open), jeme positionne sur la première ligne(fetch next) et je vais associer mes variables à chacune des colonnes de mon select , bien sûr il faut que les type des variables et des colonnes soient les mêmes.

 

open curseur_Livraison

 

      fetch next from curseur_Livraison  into @Id_Produit_Livraison  ,@Produit_Livraison  ,@Quantite_Livraison

 

Je lui dit que tant qu’il y a des lignes à traitée (c'est-à-dire leslignes issuent du select associé au CURSOR) je travaille.

 

while @@FETCH_STATUS=0

 

Begin

 

Mon travail étant le suivant : si ,pour le produit en livraison sur lequel est mon curseur actuellement,ily aune quantité en stock alors je la metà jour, sinon c’est que le produit n’existe pas et donc je fait une insertion. 

 

set @maquantite_en_stock=(select isnull(Quantite_stock,0) from dbo.Table_stock where Id_Produit_stock=@Id_Produit_Livraison)

 

      if @maquantite_en_stock<>0

 

      begin

 

            print 'update'

 

            update dbo.Table_stock  set Quantite_stock=Quantite_stock+@Quantite_Livraison where Id_Produit_stock=@Id_Produit_Livraison

 

      end

 

      else

 

      begin

 

            print 'insert'

 

            insert dbo.Table_stock values (@Id_Produit_Livraison,@Produit_Livraison,@Quantite_Livraison)

 

      end

 

Le truc c’est que je possède toutes les information de la ligne de ma table livraison puisqu’elle sont dans les différents variable liées au curseur donc autant les utilisées.

 

Une fois mon traitement fait pour une ligne, je passe à la ligne suivante en disant à mon curseur d’avancer d’une ligne et ce faisant de me remplir les variables avec les données de cette ligne. ETC…

 

fetch next from curseur_Livraison  into @Id_Produit_Livraison  ,@Produit_Livraison  ,@Quantite_Livraison

 

End

 

Une fois tous ces traitements faits il ne me reste plus qu’à sortir proprement en fermant le curseur  et en dés allouant son emplacement mémoire.

close curseur_Livraison

 

deallocate curseur_Livraison

 

Le résultat est le suivant :

result2

On voit bien que la quantité de « nutella » par exemple est passée de 10 à 40 (30 au départ + 10 livrés).

La bière qui n’était pas en stock au départ est venue s’insérer avec la quantité livrée. Etc.…

Voilà une commande qui peut venir s’insérer facilement dans des procédures stockées, des scripts et pourquoi pas des fonctions.

Posted: Jun 03 2009, 09:18 by laurentv | Comments (20) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: Privé | SQL Server

Comments

CHAUSSARD DIDIER said:

Merci beaucoup pour votre aide
Cordialement

# September 03 2010, 10:28

boiler insurance said:

1st, solid post in  [SQL Server] Utilisation de cursor, just meandering through some sites, looks to be a genuinely capable script you are employing. There is no smoke without a fire and in that respect there are no comments without postings.

# November 21 2010, 12:48

boiler said:

I am not going to tell a mistruth, you have lost me here -  [SQL Server] Utilisation de cursor.  I recognise that you thought well and you obviously know what you are writing about, but I cant pronounce that I get where you are coming from. Take care that you do not encumber yourself. Lots of writers limit themselves to items they think they are able to manage. Be confident you can go as far as your brain will allow you.

# December 22 2010, 17:07

buy term papers said:

That is easygoing to buy essay and student do not get know that your superior issue just about this topiccan survive and because of it we buy term papers.

# April 07 2011, 04:59

writing jobs said:

Big storage of materials referring to this post some people get can have, searching for freelance writing service.

# April 23 2011, 16:49

custom research paper said:

The quality of good college students increased last times. It is because you have a chance to get information how to write a research paper everywhere.

# April 29 2011, 19:16

order essays said:

If make a choice to compose the online essays, you would have to understand that this takes a hard work! Some persons spoil their written essays, because they do not know how to write! This is sorrowful, but the essay help service would assist such people any time.

# April 29 2011, 20:56

why choose us said:

Custom essays writing services compose good research essay writing connecting with this good post and the supreme outcome  about home, some students should receive costless!

# May 01 2011, 15:47

buy essay said:

It's not so simply to make a the best custom written essays, especially if you are concerned. I recommend you to notice buy essay and to be free from question that your work will be done by essay writing service

# May 02 2011, 12:05

directory submissions said:

Directory submission for cheap is not a stuff you need. Firstly you should hire experienced directory submission service. Your online business will become much better for sure.

# May 04 2011, 06:13

Tow truck insurance said:

hello, your posting is very good and different from others.you have this great info and we have unique information on tow truck insurance ...http://www.1towtruckinsurance.com/

# May 16 2011, 12:36

Truck Insurance Quote said:

Hey i have seen your post it's good..Many folks are in search of big rig insurance.we provide very great info on big rig insurance...http://www.getbigriginsurance.com/

# May 16 2011, 13:09

Tractor trailer insurance said:

c

# May 16 2011, 14:18

social bookmarking submission service said:

Do you want to generate more traffic that would be directed to your Internet site? Thence, you should use the bookmarking submissions service, because that works.

# June 01 2011, 19:17

sjr builders said:

Blog engine is a really good blog platform, Wish you best luck for blogging

# July 08 2011, 13:43

blog commenting said:

a stuff you need. Firstly you should hire experienced directory submission service. Your online business will become much better for sure.

# July 19 2011, 21:15

Funny Quotes about Love said:

I’m impressed, I must say. Really hardly ever do I encounter a blog that’s both educative and entertaining, and let me let you know, you have got hit the nail on the head. Your thought is outstanding; the issue is something that not sufficient people are speaking intelligently about. I am very joyful that I stumbled across this in my seek for something regarding this.

# July 27 2011, 12:36

personal loans said:

Have no a lot of cash to buy a house? Worry no more, because this is achievable to take the home loans to solve all the problems. Thence take a term loan to buy all you require.

# January 02 2012, 06:53

buy domain in india said:

Thanks for the nice blog. It was very useful for me. Keep sharing such ideas in the future as well. This was actually what I was looking for, and I am glad to came here! Thanks for sharing the such information with us

# January 10 2012, 09:58

android developer said:

Pretty insightful post. Never thought that it was this simple after all. I had spent a good deal of my time looking for someone to explain this subject clearly and you’re the only one that ever did that.Keep it up.

# January 16 2012, 11:14

Add comment




biuquote
  • Comment
  • Preview
Loading

captcha

*