miércoles, 2 de agosto de 2017

Recorrer una tabla sin Cursor en SQL

--Creamos una tabla temporal con un campo clave de tipo integer identity

DECLARE @Tmp_Cliente TABLE(
   Id int identity(1,1) not null primary key
  ,DNI varchar(100) not null
  ,Nombre varchar(100) null
)
--Insertamos en la tabla declarada la consulta que queremos obtener

INSERT INTO @Tmp_Cliente(Dni,nombre)
SELECT TOP 10  Dni,Nombre
FROM Cliente

DECLARE @nRegistros Int --Almacena la cantidad de registro que retorna la consulta.
SET @nRegistros=(SELECT COUNT(*) FROM @Tmp_Cliente)
DECLARE @nWhile Int --Almacenará la cantidad de veces que se esta recorriendo en el Bucle.
SET @nWhile=1

--Recorremos la tabla mediante un bucle While.
WHILE(@nRegistros>0 AND @nWhile<=@nRegistros)
BEGIN

DECLARE @Dni VARCHAR(8)
SET @Dni=(SELECT Dni FROM @Tmp_Cliente WHERE Id=@nWhile)
--usar los valores de la tabla para realizar cualquier accion (Insert, Update, Delete)
--En este caso solo se va a imprimir el Dni.

PRINT @Dni

SET @nWhile=@nWhile+1
END

No hay comentarios.:

Publicar un comentario

Macro Exportar a txt

Sub proceso () 'por luismondelo ruta = ActiveWorkbook.Path & "\" Open ruta & "ejemplo.txt" For Output As ...