Torna al Thread

USE tempdb; GO CREATE TABLE dbo.Query( Tempo smalldatetime NOT NULL, CodAttività numeric(9, 0) NOT NULL, Query nvarchar(1000) NOT NULL ); GO CREATE TABLE dbo.QueryVal( Tempo smalldatetime NOT NULL, CodAttività numeric(9, 0) NOT NULL, Valore int NULL ); GO SET NOCOUNT ON; INSERT dbo.Query VALUES('20060801', 1, 'SELECT @RowCount = COUNT(*) FROM AdventureWorks.Person.Address;'); INSERT dbo.Query VALUES('20060802', 2, 'SELECT @RowCount = COUNT(*) FROM AdventureWorks.Person.AddressType;'); INSERT dbo.Query VALUES('20060803', 3, 'SELECT @RowCount = COUNT(*) FROM AdventureWorks.Person.Contact;'); INSERT dbo.Query VALUES('20060804', 4, 'SELECT @RowCount = COUNT(*) FROM AdventureWorks.Person.ContactType;'); INSERT dbo.Query VALUES('20060805', 5, 'SELECT @RowCount = COUNT(*) FROM AdventureWorks.Person.CountryRegion;'); INSERT dbo.Query VALUES('20060806', 6, 'SELECT @RowCount = COUNT(*) FROM AdventureWorks.Person.StateProvince;'); INSERT dbo.Query VALUES('20060807', 7, 'SELECT @RowCount = COUNT(*) FROM AdventureWorks.Production.BillOfMaterials;'); SET NOCOUNT OFF; GO /* Definisco la stored procedure dbo.up_QueryVal */ CREATE PROCEDURE dbo.up_QueryVal AS DECLARE @Tempo smalldatetime; DECLARE @CodAttività numeric(9, 0); DECLARE @Query nvarchar(1000); DECLARE @Valore int; /* Dichiaro il cursore */ DECLARE Cursore CURSOR FOR SELECT * FROM dbo.Query FOR READ ONLY; /* Lo apro */ OPEN Cursore; /* Prima lettura */ FETCH NEXT FROM Cursore INTO @Tempo, @CodAttività, @Query; /* Loop */ WHILE @@FETCH_STATUS = 0 BEGIN /* Eseguo la query */ EXEC sp_executesql @Query, N'@RowCount int OUTPUT', @RowCount = @Valore OUTPUT; /* Valorizzo la tabella QueryVal */ INSERT dbo.QueryVal VALUES(@Tempo, @CodAttività, @Valore); /* Letture successive */ FETCH NEXT FROM Cursore INTO @Tempo, @CodAttività, @Query; END /* Pulizia */ CLOSE Cursore; DEALLOCATE Cursore; GO /* Eseguo la stored procedure dbo.up_QueryVal */ EXEC dbo.up_QueryVal; GO /* Vediamo... */ SELECT * FROM dbo.QueryVal; GO /* Output: Tempo CodAttività Valore ----------------------- --------------------------------------- ----------- 2006-08-01 00:00:00 1 19614 2006-08-02 00:00:00 2 6 2006-08-03 00:00:00 3 19972 2006-08-04 00:00:00 4 20 2006-08-05 00:00:00 5 238 2006-08-06 00:00:00 6 181 2006-08-07 00:00:00 7 2679 (7 row(s) affected) */ /* Pulizia */ DROP TABLE dbo.Query, dbo.QueryVal; DROP PROCEDURE dbo.up_QueryVal;
Copyright © dotNetHell.it 2002-2024
Running on Windows Server 2008 R2 Standard, SQL Server 2012 & ASP.NET 3.5