Visual 2010 sql server 2008

139
20/12/2011 Programación Aplicada I | SALAZAR CACHO, Iris Nohely UNC MANUAL DE PROGRAMACIÓN APLICADA I

description

 

Transcript of Visual 2010 sql server 2008

Page 1: Visual 2010 sql server 2008

20/12/2011

Programación Aplicada I | SALAZAR CACHO, Iris Nohely

UNC MANUAL DE PROGRAMACIÓN APLICADA I

Page 2: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 2

I. BASES DE DATOS Y VISUAL BASIC

Visual Basic no es un administrador de Bases de Datos, sólo utiliza un

gestor de Bases de Datos, para nuestro caso será, Microsoft SQL Server

2008; para permitir la visualización de una manera más estética de los

datos, también para poder mostrar, o realizar algunos cambios en alguna

base de datos.

Es necesario tener conocimiento del concepto de algunas sentencias que

utilizaremos en la segunda parte del curso Programación Aplicada I:

.1. Espacio de nombres “System.Data.SqlClient”:

Es el proveedor de datos de .NET Framework para SQL Server. Un

proveedor de datos de .NET Framework para SQL Server describe

una colección de clases utilizada para tener acceso a una base de

datos de SQL Server en el espacio administrado.

.2. SqlConnection (Clase):

Representa una conexión abierta con una base de datos de SQL

Server. Esta clase no se puede heredar.

Page 3: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 3

.3. SqlDataAdapter (Clase):

Representa un conjunto de comandos de datos y una conexión de

base de datos que se utilizan para rellenar un DataSet y actualizar

una base de datos de SQL Server. Esta clase no se puede heredar.

SqlDataAdapter, se utiliza como un puente entre DataSet y SQL

Server para recuperar y guardar datos. SqlDataAdapter

proporciona este puente mediante la asignación de Fill, que cambia

los datos en DataSet para que coincidan con los datos del origen de

datos.

.4. SqlDataAdapter.Fill (Método):

Rellena un objeto DataSet o un objeto DataTable. Agrega filas a

DataSet o las actualiza para hacerlas coincidir con las filas del

origen de datos utilizando los nombres de DataSet y DataTable.

.5. DataSet (Clase):

Representa una caché de memoria interna de datos. DataSet, que

es una caché de memoria interna de datos recuperados de un

origen de datos, representa un componente fundamental de la

arquitectura de ADO.NET. DataSet está compuesto por una

colección de objetos DataTable que se pueden relacionar entre

ellos mediante objetos DataRelation.

Sintaxis:

SqlDataAdapter.Fill(DataSet, String)

Page 4: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 4

.6. Ejemplo de conexiones a una Base de Datos:

Dim conex As New SqlConnection("server=.;database = Northwind;trusted_connection=true")

Conex: Nombre de la conexión a la base de datos.

Server: Es el nombre del servidor; en este caso, la conexión es local, también

podemos escribir (local), localhost; si la conexión no es local, se debe

escribir el nombre propio de dicha conexión.

Database: Indica el nombre de la base de datos a la cual se desea conectar.

Trusted_connection: Permite conectarse a la base de datos con el mecanismo de

autenticación de Windows.

"Data Source=. ; Initial Catalog = Northwind; Integrated Security= True"

Data Source: Es el nombre del servidor; en este caso, la conexión es local; si la

conexión no es local, se debe escribir el nombre propio de dicha conexión.

Initial Catalog: Indica el nombre de la base de datos a la cual se desea conectar.

Integrated Security: Permite conectarse a la base de datos con el mecanismo de

autenticación de Windows.

Page 5: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 5

PRÁCTICA I

1. VISUALIZAR LOS ESTUDIANTES QUE ESTÁN EN UNA BASE DE

DATOS.

Se tiene la información en una hoja de Excel y es necesario trasferir

esos datos a SQL, para ello seguiremos los siguientes pasos:

En SQL, creamos la nueva tabla en la base de datos Northwind

(la base de datos es opcional, si se desea se puede crear una

base de datos o crear la tabla en otras bases de datos

existentes) y seleccionamos el tipo de dato adecuado para

cada fila y clave primaria:

Page 6: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 6

Guardamos el registro de datos de Excel en formato con

extensión csv (delimitado por comas):

Obtendremos lo siguiente (para visualizar el archivo así, es

necesario hacer un clic derecho sobre el archivo y escoger la

opción editar)

Page 7: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 7

Para poder obtener sólo los datos de los alumnos, debemos

eliminar la primera fila que corresponde a los encabezados:

Escribiremos el siguiente código SQL Transact para poder

migrar los datos a la tabla:

Ahora, ya tenemos los datos en una tabla de una base de datos

y podemos ejecutar sobre ellos códigos SQL Transact:

BULKINSERT ESTUDIANTES

FROM 'F:\UNc\PAI\alumnos.csv' ruta del archivowith(

FIELDTERMINATOR=',', Indica que al encontrar una coma éste termina e inicia otro.ROWTeRMINATOR='\n')

select *from estudiantes

Page 8: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 8

Luego de tener los datos ya en el gestor SQL, haremos el

trabajo en visual, necesitaremos utilizar la herramienta

DataGriediew y escribiremos el siguiente código:

Imports System.Data.SqlClient

Public Class Form1

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) HandlesMyBase.Load

Dim conex As New SqlConnection("server=.;database = Northwind;trusted_connection=true")

Dim datos As New SqlDataAdapter("select * from estudiantes", conex)Dim ds As New Data.DataSet

datos.Fill(ds, "Alumnos")DGV1.DataSource = ds.Tables("alumnos")

End Sub

End Class

Page 9: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 9

2. VISUALIZAR LOS DATOS DE LOS ALUMNOS DESDE LA WEB:

Crearemos un formulario web:

Utilizaremos la herramienta GriedView:

Page 10: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 10

El código en visual será:

Imports System.Data.SqlClient

Public Class WebForm1

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)Handles Me.Load

Dim conex As New SqlConnection("server=.;database = Northwind;trusted_connection=true")

Dim datos As New SqlDataAdapter("select * from estudianTes", conex)

Dim ds As New Data.DataSet

datos.Fill(ds, "Alumnos")

GridView1.DataSource = ds.Tables("Alumnos")GridView1.DataBind()

End Sub

End Class

Page 11: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 11

3. CREAR UN PROGRAMA QUE PERMITA VISUALIZAR LOS DATOS DE

UN ESTUDIANTE CUYO CÓDIGO ANR SEA INGRESADO MEDIANTE

UN LECTOR DE CÓDIGO DE BARRAS:

Crearemos un procedimiento almacenado en SQL, para poder

usar el programa las veces que deseemos y para facilitar el

desarrollo de este ejercicio:

Código en visual:

CREATE PROC BUSCAR_ALUMNO@ID CHAR(10)ASSELECT * FROM ESTUDIANTESWHERE IDESTUDIANTE =@ID

Imports System.Data.SqlClient

Public Class Form3

Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs)

Handles TextBox1.KeyPress

If e.KeyChar = Chr(13) Then

Dim conex2 As New SqlConnection("server=.; database=northwind;

trusted_connection=true ")

Dim traerdatos As New SqlDataAdapter("select * from estudiantes where

idestudiante=@id ", conex2)

traerdatos.SelectCommand.Parameters.Add("@id", SqlDbType.Char,10).Value =

TextBox1.Text

Dim contenedordatos As New Data.DataSet

traerdatos.Fill(contenedordatos, "Alumnos")

DataGridView1.DataSource = contenedordatos.Tables("Alumnos")

End If

End Sub

End Class

Page 12: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 12

PRÁCTICA II – TRABAJO DE CICLO

La novena práctica consiste en crear un menú con opciones que nos

permitan visualizar distintas y numerosas consultas a la base de

datos Northwind; así como también hacer algunas modificaciones a

los datos de la misma:

1. REALIZAR UNA CONEXIÓN QUE SIRVA PARA TODOS LOS

FORMULARIOS QUE SE IMPLEMENTARÁN

Es necesario agregar un módulo; para ello, sobre el

proyecto clic derecho y luego elegir la opción agregar;

finalmente clic en la opción módulo:

NOTA: Cuando el lector de código de barras

lee el código simula un enter al finalizar; es

por eso que en el código en visual se programó

el código bajo la condición del enter.

Page 13: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 13

Se nos mostrará la siguiente ventana y tendremos que

escribir un nombre para la conexión, la

denominaremos “GLOBALES”:

Page 14: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 14

Finalmente, el código de la conexión es:

2. CREAR UN MENÚ QUE NOS MUESTRE LAS SIGUIENTES

OPCIONES:

Mantenimiento

Reportes

Consultas

Acerca de

Module GLOBALESPublic conex As New

System.Data.SqlClient.SqlConnection("server=.;database=northwind;trusted_connection=true")

End Module

Page 15: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 15

3. VISUALIZAR EL NÚMERO DE PRODUCTOS POR CATEGORÍA:

Código SQL:

Código visual, para poder mostrar los datos:

Código visual para poder mostrar el formulario que

contiene dichos datos:

CREATE PROC QUERY1ASSELECT CATEGORYNAME,COUNT(*) AS TOTALFROM Categories AS C INNER JOIN Products AS PON C.CategoryID =P.CategoryIDGROUP BY CategoryNameORDER BY CategoryName

Imports System.Data.SqlClient

Public Class consulta01Private Sub consulta01_Load(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles MyBase.LoadDim datos As New SqlDataAdapter("QUERY1", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProceduredatos.Fill(ds, "QUERY1")dg.DataSource = ds.Tables("QUERY1")

End SubEnd Class

Private Sub ProductosPorCategoriaToolStripMenuItem_Click(sender As System.Object,e As System.EventArgs) Handles ProductosPorCategoriaToolStripMenuItem.Click

Dim Fm As New consulta01Fm.MdiParent = MeFm.Show()

End Sub

Page 16: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 16

4. REALIZAR UNA CONSULTA QUE PERMITA VER CÓDIGO DEL

PRODUCTO, NOMBRE DEL PRODUCTO, PRECIO DEL PRODUCTO,

STOCK, NOMBRE DEL PROVEEDOR Y CATEGORÍA DEL

PRODUCTO, LAS CATEGORÍAS SE MOSTRARÁN EN UNA LISTA

DESPLEGABLE:

Haremos una conexión especial para la lista

desplegable, seguiremos los siguientes pasos:

a) Clic sobre el triángulo de la esquina superior derecha

de la lista, luego clic en la opción desplegable de

“Origen de Datos” y se nos mostrará la siguiente

ventana, elegiremos entonces la opción “Agregar

origen de datos del proyecto”:

NOTA: El código en visual, que nos

permite mostrar los formularios que

deseamos ver es similar, sólo es necesario

cambiar los nombres de los formularios.

Page 17: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 17

b) Aparecerá la siguiente ventana y luego clic sobre el

botón “Siguiente”

c) En esta ventana, seleccionaremos “Conjunto de

Datos” y luego clic en el botón “Siguiente”:

Page 18: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 18

d) Clic en el botón “Nueva Conexión”

e) Se mostrará una ventana que solicita llenar algunos datos

sobre el tipo de conexión y el nombre de la base de datos a

la que se desea conectar, luego probaremos la conexión

para evitar errores posteriores:

Page 19: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 19

f) Se nos presentará la siguiente ventana, en la cual, debemos

elegir que objetos deseamos tener en el conjunto de datos:

g) Finalmente, tendremos especial cuidado al seleccionar qué

datos debemos seleccionar en las etiquetas: Si la etiqueta es

“Mostrar Miembro” hace referencia a lo que se va a mostrar;

pero si la etiqueta es “Miembro de valor” lo que contiene son

los valores de los datos:

Page 20: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 20

Código SQL:

Código en visual:

create proc query2@cate intasselect ProductID ,ProductName ,UnitPrice,UnitsInStock ,companyname,CategoryIDfrom Products as p inner join Suppliers as son p.SupplierID =s.SupplierIDwhere CategoryID =@cate

Imports System.Data.SqlClientPublic Class Form3

Private Sub ListBox1_SelectedIndexChanged(ByVal sender AsSystem.Object, ByVal e As System.EventArgs) HandlesListBox1.SelectedIndexChanged

Dim datos As New SqlDataAdapter("query2", conex)datos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@cate", SqlDbType.Int).Value =

ListBox1.SelectedValueDim ds As New Data.DataSetdatos.Fill(ds, "tablas")DataGridView1.DataSource = ds.Tables("tablas")

End SubEnd Class

Page 21: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 21

5. MOSTRAR LOS SIGUIENTES DATOS DE LOS PRODUCTOS:

NOMBRE, PRECIO, CATEGORÍA Y PROVEEDOR; SÓLO DE LOS

PRODUCTOS QUE ESTÉN DENTRO DE UN RANGO DE PRECIOS:

Código SQL:

Código en visual:

create proc query3@menor int,@mayor intasselect ProductName , UnitPrice, CategoryName ,companynamefrom Products as p inner join Categories as con p.CategoryID =c.CategoryID inner join Suppliers as son p.SupplierID =s.SupplierIDwhere UnitPrice between @menor And @mayor

Imports System.Data.SqlClient

Public Class Form4

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.ClickDim datos As New SqlDataAdapter("query3", conex)datos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@menor", SqlDbType.Int).Value = TextBox1.Textdatos.SelectCommand.Parameters.Add("@mayor", SqlDbType.Int).Value = TextBox2.TextDim ds As New Data.DataSetdatos.Fill(ds, "t")DataGridView1.DataSource = ds.Tables(0)

End SubEnd Class

Page 22: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 22

6. MOSTRAR NOMBRE, PRECIO, CATEGORÍA Y PROVEEDOR DE

LOS PRODUCTOS QUE EMPIECEN CON UNA DETERMINADA

LETRA:

Código SQL:

create proc query4@nom varchar(10)asselect ProductName ,UnitPrice, CategoryID ,SupplierIDfrom productswhere ProductName like @nom+'%'

Page 23: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 23

Código en Visual:

Imports System.Data.SqlClient

Public Class Form5

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e

As System.Windows.Forms.KeyPressEventArgs) Handles

TextBox1.KeyPress

Dim datos As New SqlDataAdapter("query4", conex)

datos.SelectCommand.CommandType =

CommandType.StoredProcedure

datos.SelectCommand.Parameters.Add("@nom",

SqlDbType.NVarChar, 10).Value = TextBox1.Text

Dim ds As New Data.DataSet

datos.Fill(ds, "productitos")

DataGridView1.DataSource = ds.Tables(0)

End Sub

Page 24: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 24

7. VISUALIZAR LOS PRODUCTOS QUE PERTENECEN A UN

DETERMINADO PORVEEDOR:

Código SQL:

Código en Visual:

create proc query5@id intasselect ProductName ,UnitPrice ,UnitsInStock,s.SupplierID, s.CompanyNamefrom Products as p inner join Suppliers as son p.SupplierID =s .SupplierIDwhere s.SupplierID = @id

Imports System.Data.SqlClientPublic Class Form6

Private Sub Form6_Load(sender As System.Object, e As System.EventArgs)Handles MyBase.Load

'TODO: esta línea de código carga datos en la tabla'PAIDataSet1.Suppliers' Puede moverla o quitarla según sea necesario.

Me.SuppliersTableAdapter1.Fill(Me.PAIDataSet1.Suppliers)End Sub

Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e AsSystem.EventArgs) Handles ListBox1.SelectedIndexChanged

Dim datos As New SqlDataAdapter("query5", conex)datos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value =

ListBox1.SelectedValueDim ds As New Data.DataSetdatos.Fill(ds, "prod")DataGridView1.DataSource = ds.Tables(0)

End SubEnd Class

Page 25: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 25

Page 26: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 26

8. VER LOS DETALLES DE UNA ORDEN DE COMPRA:

Código SQL:

Código en visual:

create proc query6@oid as intasselect od.OrderID,p.ProductId,ProductName ,p.UnitPrice ,Quantityfrom Orders as o inner join [Order Details] as odon o.OrderID =od.OrderID inner join Products as pon od.ProductID =p.ProductIDwhere od.OrderID =@oid

Imports System.Data.SqlClientPublic Class Form7

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) HandlesButton1.Click

Dim datos As New SqlDataAdapter("query6", conex)datos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@oid", SqlDbType.Int).Value = TextBox1.TextDim ds As New Data.DataSetdatos.Fill(ds, "p")DataGridView1.DataSource = ds.Tables(0)

End SubEnd Class

Page 27: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 27

9. PRODUCTOS CON STOCK Y PRODUCTOS SIN STOCK:

Código SQL:

Código en Visual:

Productos con stock:create proc query8asselect ProductID ,ProductName ,UnitPrice ,UnitsInStockfrom Productswhere UnitsInStock > 0

Productos sin stock:create proc query8asselect ProductID ,ProductName ,UnitPrice ,UnitsInStockfrom Productswhere UnitsInStock = 0

Imports System.Data.SqlClient

Public Class Form8

Private Sub RadioButton1_CheckedChanged(sender As System.Object, e AsSystem.EventArgs) Handles RadioButton1.CheckedChanged

Dim datos As New SqlDataAdapter("query7", conex)datos.SelectCommand.CommandType = CommandType.StoredProcedureDim ds As New Data.DataSetdatos.Fill(ds, "p")DataGridView1.DataSource = ds.Tables(0)

End Sub

Private Sub RadioButton2_CheckedChanged(sender As System.Object, e AsSystem.EventArgs) Handles RadioButton2.CheckedChanged

Dim datos As New SqlDataAdapter("query8", conex)datos.SelectCommand.CommandType = CommandType.StoredProcedureDim ds As New Data.DataSetdatos.Fill(ds, "p")DataGridView1.DataSource = ds.Tables(0)

End Sub

Private Sub Form8_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles MyBase.Load

End SubEnd Class

Page 28: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 28

Page 29: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 29

10. MOSTRAR LOS PRODUCTOS VIGENTES Y LOS

DESCONTINUADOS:

Código SQL:

Código Visual:

create proc query9@value as bitasselect ProductID , ProductName , UnitPrice ,Discontinuedfrom Productswhere Discontinued=@value

Public Class Form9

Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs)Handles CheckBox1.CheckedChanged

Dim datos As New SqlDataAdapter("query9", conex)datos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@value", SqlDbType.Bit).Value = CheckBox1.Checked

Dim ds As New Data.DataSetdatos.Fill(ds, "a")DataGridView1.DataSource = ds.Tables("a")

End Sub

End Class

Imports System.Data.SqlClient

Public Class Form9

Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs) HandlesCheckBox1.CheckedChanged

Dim valor As Integer

If CheckBox1.Checked Thenvalor = 1

Elsevalor = 0

End IfDim datos As New SqlDataAdapter("query9", conex)datos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@value", SqlDbType.Bit).Value = valorDim ds As New Data.DataSetdatos.Fill(ds, "a")DataGridView1.DataSource = ds.Tables("a")

End Sub

End Class

Page 30: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 30

Page 31: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 31

PRÁCTICA III

CREACIÓN DE LA CONEXIÓN:

1. EN UN LISTBOX O COMBOBOX, COLOCAR EL SIGUIENTE TEXTO (SON LOS

TIPOS DE BUSQUEDA):

Comienza conTermina conContiene aNo contiene aExactamente igual a

El proceso es seleccionar un tipo de búsqueda en la Lista, luego escribir un texto enel TextBox y al darle <ENTER> al TextBox, se debe filtrar el DatagridView por elnombre del producto, respetando el tipo de búsqueda seleccionado.

Los datos que deben salir en el DatagridView son: ProductId ProductName,UnitPrice, UnitsInStock, Categoryname, Companyname (Suppliers).

a) DISEÑO:

Module CONEXIÓN

Public conex As New

System.Data.SqlClient.SqlConnection("server=.;database=northwind;trusted_connection=true")

End Module

Page 32: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 32

b) CONSULTA SQL:

create procedure definido@nombre as nvarchar(40),@tipo as intas

if @tipo=0SELECT ProductId, ProductName, UnitPrice, UnitsInStock,Categoryname, CompanynameFROM Categories AS C INNER JOIN Products AS P ON C.CategoryID=P.CategoryID INNER JOINSuppliers AS S ON P.SupplierID= S.SupplierIDWHERE ProductName LIKE @NOMBRE+'%'

else if @tipo=1SELECT ProductId, ProductName, UnitPrice, UnitsInStock,Categoryname, CompanynameFROM Categories AS C INNER JOIN Products AS P ON C.CategoryID=P.CategoryID INNER JOINSuppliers AS S ON P.SupplierID= S.SupplierIDWHERE ProductName LIKE '%'+@NOMBRE

else if @tipo=2SELECT ProductId, ProductName, UnitPrice, UnitsInStock,Categoryname, CompanynameFROM Categories AS C INNER JOIN Products AS P ON C.CategoryID=P.CategoryID INNER JOINSuppliers AS S ON P.SupplierID= S.SupplierIDWHERE ProductName LIKE '%'+@NOMBRE + '%'

else if @tipo=3SELECT ProductId, ProductName, UnitPrice, UnitsInStock,Categoryname, CompanynameFROM Categories AS C INNER JOIN Products AS P ON C.CategoryID=P.CategoryID INNER JOINSuppliers AS S ON P.SupplierID= S.SupplierIDWHERE ProductName NOT LIKE '%'+@NOMBRE+'%'

elseSELECT ProductId, ProductName, UnitPrice, UnitsInStock,Categoryname, CompanynameFROM Categories AS C INNER JOIN Products AS P ON C.CategoryID=P.CategoryID INNER JOINSuppliers AS S ON P.SupplierID= S.SupplierIDWHERE ProductName LIKE @NOMBRE

Page 33: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 33

c) CÓDIGO EN VISUAL:

d) PANTALLAS:

Private Sub TextBox1_KeyPress(sender As Object, e AsSystem.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

If e.KeyChar = ChrW(13) Then

Dim datos As New SqlDataAdapter("definido", conex)datos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@NOMBRE", SqlDbType.NVarChar,

40).Value = TextBox1.Textdatos.SelectCommand.Parameters.Add("@tipo", SqlDbType.Int).Value =

ListBox1.SelectedIndexDim ds As New Data.DataSetdatos.Fill(ds, "p")DataGridView1.DataSource = ds.Tables(0)

Page 34: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 34

Page 35: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 35

Page 36: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 36

2. EN UN GRUPO DE RADIOBUTTON, COLOCAR LOS FILTROS COMO SE MUESTRA

EN LA PANTALLA.

El procedimiento es seleccionar un filtro, luego darle un click en el botón, paraque aparezcan los datos de los Productos en el DataGridView.

Los campos a mostrar en el DataGridView son: ProductName, UnitPrice,UnitsinStock, CategoryID, Discontinued.

a) DISEÑO:

Page 37: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 37

b) CONSULTAS SQL:

CREATE PROCEDURE CONSULTA6ASSELECT ProductName, UnitPrice, UnitsinStock, C.CategoryID,DiscontinuedFROM PRODUCTS AS P INNER JOIN CATEGORIES AS C ONP.CategoryID = C.CategoryIDWHERE UnitsInStock >0

CREATE PROCEDURE CONSULTA7ASSELECT ProductName, UnitPrice, UnitsinStock, C.CategoryID,DiscontinuedFROM PRODUCTS AS P INNER JOIN CATEGORIES AS C ONP.CategoryID = C.CategoryIDWHERE Discontinued = '0'

CREATE PROCEDURE CONSULTA8@CAT INTASSELECT ProductName, UnitPrice, UnitsinStock, C.CategoryID,DiscontinuedFROM PRODUCTS AS P INNER JOIN CATEGORIES AS C ONP.CategoryID = C.CategoryIDWHERE C.CategoryID =@CAT

ALTER PROCEDURE CONSULTA9ASSELECT ProductName, UnitPrice, UnitsinStock, C.CategoryID,DiscontinuedFROM PRODUCTS AS P INNER JOIN CATEGORIES AS C ONP.CategoryID = C.CategoryID

Page 38: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 38

c) CÓDIGO EN VISUAL:

Imports System.Data.SqlClient

Public Class SEGUNDO

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)

Handles Button1.Click

If RadioButton1.Checked Then

Dim datos As New SqlDataAdapter("CONSULTA6", conex)

datos.SelectCommand.CommandType = CommandType.StoredProcedure

Dim ds As New Data.DataSet

datos.Fill(ds, "p")

DataGridView1.DataSource = ds.Tables(0)

ElseIf RadioButton2.Checked Then

Dim datos As New SqlDataAdapter("CONSULTA7", conex)

datos.SelectCommand.CommandType = CommandType.StoredProcedure

Dim ds As New Data.DataSet

datos.Fill(ds, "p")

DataGridView1.DataSource = ds.Tables(0)

ElseIf RadioButton3.Checked Then

Dim datos As New SqlDataAdapter("CONSULTA8", conex)

datos.SelectCommand.CommandType = CommandType.StoredProcedure

datos.SelectCommand.Parameters.Add("@CAT", SqlDbType.Int).Value =

TextBox1.Text

Dim ds As New Data.DataSet

datos.Fill(ds, "p")

DataGridView1.DataSource = ds.Tables(0)

Else

Dim datos As New SqlDataAdapter("CONSULTA9", conex)

datos.SelectCommand.CommandType = CommandType.StoredProcedure

Dim ds As New Data.DataSet

datos.Fill(ds, "p")

DataGridView1.DataSource = ds.Tables(0)

End If

End Sub

End Class

Page 39: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 39

d) PANTALLAS:

Page 40: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 40

Page 41: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 41

3. IMPLEMENTAR LA INTERFACE DEL EJERCICIO 2, ESTA VEZ SIN ELCOMMANDBUTTON, LA BÚSQUEDA SE HARÁ AL SELECCIONAR ELRADIOBUTTON (EN EL CASO DEL FILTRO DE CATEGORÍA, SE HARÁ CON ELENTER DEL TEXTBOX).

a) DISEÑO:

b) CONSULTAS SQL:

CREATE PROCEDURE CONSULTA6ASSELECT ProductName, UnitPrice, UnitsinStock, C.CategoryID, DiscontinuedFROM PRODUCTS AS P INNER JOIN CATEGORIES AS C ON P.CategoryID = C.CategoryIDWHERE UnitsInStock >0

CREATE PROCEDURE CONSULTA7ASSELECT ProductName, UnitPrice, UnitsinStock, C.CategoryID, DiscontinuedFROM PRODUCTS AS P INNER JOIN CATEGORIES AS C ON P.CategoryID = C.CategoryIDWHERE Discontinued = '0'

CREATE PROCEDURE CONSULTA8@CAT INTASSELECT ProductName, UnitPrice, UnitsinStock, C.CategoryID, DiscontinuedFROM PRODUCTS AS P INNER JOIN CATEGORIES AS C ON P.CategoryID = C.CategoryIDWHERE C.CategoryID =@CAT

ALTER PROCEDURE CONSULTA9ASSELECT ProductName, UnitPrice, UnitsinStock, C.CategoryID, DiscontinuedFROM PRODUCTS AS P INNER JOIN CATEGORIES AS C ON P.CategoryID = C.CategoryID

Page 42: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 42

c) CÓDIGO EN VISUAL:

Imports System.Data.SqlClient

Public Class TERCERO

Private Sub RadioButton1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles

RadioButton1.CheckedChanged

If RadioButton1.Checked Then

Dim datos As New SqlDataAdapter("CONSULTA6", conex)

datos.SelectCommand.CommandType = CommandType.StoredProcedure

Dim ds As New Data.DataSet

datos.Fill(ds, "p")

DataGridView1.DataSource = ds.Tables(0)

End If

End Sub

Private Sub RadioButton2_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles

RadioButton2.CheckedChanged

If RadioButton2.Checked Then

Dim datos As New SqlDataAdapter("CONSULTA7", conex)

datos.SelectCommand.CommandType = CommandType.StoredProcedure

Dim ds As New Data.DataSet

datos.Fill(ds, "p")

DataGridView1.DataSource = ds.Tables(0)

End If

End Sub

Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles

TextBox1.KeyPress

If e.KeyChar = ChrW(13) Then

If RadioButton3.Checked Then

Dim datos As New SqlDataAdapter("CONSULTA8", conex)

datos.SelectCommand.CommandType = CommandType.StoredProcedure

datos.SelectCommand.Parameters.Add("@CAT", SqlDbType.Int).Value = TextBox1.Text

Dim ds As New Data.DataSet

datos.Fill(ds, "p")

DataGridView1.DataSource = ds.Tables(0)

End If

End If

End Sub

Private Sub RadioButton4_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles

RadioButton4.CheckedChanged

If RadioButton4.Checked Then

Dim datos As New SqlDataAdapter("CONSULTA19", conex)

datos.SelectCommand.CommandType = CommandType.StoredProcedure

Dim ds As New Data.DataSet

datos.Fill(ds, "p")

DataGridView1.DataSource = ds.Tables(0)

End If

End Sub

End Class

Page 43: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 43

d) PANTALLAS:

Page 44: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 44

Page 45: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 45

4. COLOCAR UN OBJETO MONTHCALENDAR, UN DATAGRIDVIEW Y UN TEXTBOX

(SERÁ TEMPORAL, UNA VEZ SE IMPLEMENTE EL FORMULARIO, SE ELIMINARÁ)

El GridView debe mostrar: OrderId, OrderDate, ProductName, UnitPrice, Quantity.

Al seleccionar una fecha, automáticamente se debe filtrar el DatGridView por el

campo OrderDate, se debe configurar el MonthCalendar, para que la fecha inicie el

01/01/1996 y finalice el 31/12/1997 (fechas del campo OrderDate de la Tabla Orders).

a) DISEÑO:

Page 46: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 46

b) CÓDIGO SQL:

c) CÓDIGO VISUAL:

CREATE PROCEDURE CONSULTA10@FECHA DATETIMEASSELECT O.OrderId, OrderDate, ProductName,P.UnitPrice, QuantityFROM Orders AS O INNER JOIN [Order Details] AS OD ONO.OrderID = OD.OrderID INNER JOIN Products AS PON OD.ProductID= P.ProductIDWHERE O.OrderDate = @FECHA

Imports System.Data.SqlClient

Public Class CUARTO

Private Sub MonthCalendar1_DateSelected(sender As

Object, e As System.Windows.Forms.DateRangeEventArgs)

Handles MonthCalendar1.DateSelected

TextBox1.Text = CStr(MonthCalendar1.SelectionStart)

End Sub

Private Sub MonthCalendar1_DateChanged(sender As

System.Object, e As

System.Windows.Forms.DateRangeEventArgs) Handles

MonthCalendar1.DateChanged

Dim datos As New SqlDataAdapter("CONSULTA10",

conex)

datos.SelectCommand.CommandType =

CommandType.StoredProcedure

datos.SelectCommand.Parameters.Add("@FECHA",

SqlDbType.DateTimeOffset).Value =

MonthCalendar1.SelectionStart

Dim ds As New Data.DataSet

datos.Fill(ds, "p")

DataGridView1.DataSource = ds.Tables(0)

End Sub

End Class

Page 47: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 47

d) PANTALLAS:

Page 48: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 48

II. RELACIONES DE LAS TABLAS EN VISUAL:

En la base de datos Northwind podemos observar que existen tablas

relacionadas y que de algunas de ellas pasa su clave principal como clave

foránea; esto permite que podamos realizar aplicaciones bajo el mismo

concepto de relación; en la siguiente práctica implementaremos

ejercicios de este tipo; en muchos casos será necesaria la

implementación de dos o más procedimientos almacenados en la Base

de Datos Northwind.

PRÁCTICA IV

1. MOSTRAR CATEGORÍA, NOMBRE DE LA CATEGORÍA Y DESCRIPCIÓN DE LOS

PRODUCTOS, A LA VEZ MOSTRAR TODOS LOS PRODUCTOS QUE

PERTENECEN A CIERTA CATEGORÍA (SE ELEGIRÁ MEDIANTE UN CLIC DE

QUÉ CATEGORÍA DESEAMOS VER LOS PRODUCTOS):

Código SQL:

Mostrar todas las categorías:

create procedure QUERY14asselect categoryid, categoryname,descriptionfrom Categories

Mostrar productos de una determinada categoría:

create procedure QUERY14i@cat intasselect productid, productname, unitprice, c.categoryidfrom products as p inner join Categories as c

on p.CategoryID = c.CategoryIDwhere p.CategoryID = @cat

Page 49: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 49

Código en visual:

Public Class Form14

Private Sub Form14_Load(sender As System.Object, e As System.EventArgs)Handles MyBase.Load

Dim datos As New SqlDataAdapter("QUERY14", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProceduredatos.Fill(ds, "prod1")dgv_cab.DataSource = ds.Tables(0)

End Sub

Private Sub dgv_cab_CellEnter(sender As Object, e AsSystem.Windows.Forms.DataGridViewCellEventArgs) Handles dgv_cab.CellEnter

Dim datos As New SqlDataAdapter("QUERY14i", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@cat", SqlDbType.Int).Value =

dgv_cab.Rows(e.RowIndex).Cells(0).Valuedatos.Fill(ds, "prod2")dgv_det.DataSource = ds.Tables(0)

End Sub

End Class

Page 50: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 50

Page 51: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 51

Page 52: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 52

Page 53: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 53

2. MOSTRAR LAS ÓRDENES REALIZADAS, LUEGO MOSTRAR LOS DETALLES DE

CIERTA ORDEN (SE SELECCIONARÁ LA ORDEN PARA VER LOS DETALLES):

Código SQL:

Mostrar todas las órdenes:

CREATE PROCEDURE QUERY15ASSELECT OrdERID, ORDERDATE, FREIGHTFROM Orders

Mostrar detalles de una determinada orden:

CREATE PROCEDURE QUERY15i@IDE INTASSELECT OD.ORDERID, O.ORDERDATE, OD.PRODUCTID,P.PRODUCTNAME, P.UNITPRICE, QuantityFROM Orders AS O INNER JOIN [Order Details] ASOD

ON O.OrderID = OD.OrderIDINNER JOIN Products AS PON OD.ProductID =

P.ProductIDWHERE O.OrderID = @IDE

Page 54: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 54

Código en Visual:

Imports System.Data.SqlClient

Public Class Form15

Private Sub Form15_Load(sender As System.Object, e As System.EventArgs) HandlesMyBase.Load

Dim datos As New SqlDataAdapter("QUERY15", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProceduredatos.Fill(ds, "prod1")dgv_cab.DataSource = ds.Tables(0)

End Sub

Private Sub dgv_cab_CellEnter(sender As Object, e AsSystem.Windows.Forms.DataGridViewCellEventArgs) Handles dgv_cab.CellEnter

Dim datos As New SqlDataAdapter("QUERY15i", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@IDE", SqlDbType.Int).Value =

dgv_cab.Rows(e.RowIndex).Cells(0).Valuedatos.Fill(ds, "prod2")dgv_det.DataSource = ds.Tables(0)

End Sub

End Class

Page 55: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 55

Page 56: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 56

3. MOSTRAR LA FOTO DE LOS EMPLEADOS, SE MOSTRARÁ LA RELACIÓN DE

EMPLEADOS Y SE SELECCIONARÁ ALGUNO:

Código SQL:

Código en Visual:

Mostrar la relación de empleados:

CREATE PROCEDURE QUERY16ASSELECT EmployeeID , LastName , FirstNameFROM Employees

Mostrar un sólo empleado, utilizamos un parámetro:

CREATE PROCEDURE QUERY16i@ID INTASSELECT LastNameFROM EmployeesWHERE EMPLOYEEID = @ID

Imports System.Data.SqlClientPublic Class Form16

Private Sub Form16_Load(sender As System.Object, e As System.EventArgs) HandlesMyBase.Load

Dim datos As New SqlDataAdapter("QUERY16", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProceduredatos.Fill(ds, "QUERY16")dgv_cab.DataSource = ds.Tables(0)

End Sub

Private Sub dgv_cab_CellContentClick(sender As System.Object, e AsSystem.Windows.Forms.DataGridViewCellEventArgs) Handles dgv_cab.CellContentClick

Dim datos As New SqlDataAdapter("QUERY16i", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProcedureDim index As Integerindex = dgv_cab.Rows(e.RowIndex).Cells(0).Value

datos.SelectCommand.Parameters.Add("@ID", SqlDbType.Int).Value = indexdatos.Fill(ds, "QUERY16i")PictureBox1.Image = Image.FromFile("C:\Documents and Settings\IRIS

NOHELY\Escritorio\imag música\n_n\" + CStr(index) + ".jpg")

End SubEnd Class

Page 57: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 57

Page 58: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 58

Page 59: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 59

Page 60: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 60

4. MOSTRAR LAS ÓRDENES REALIZADAS POR CIERTO EMPLEADO, SE

PRESENTARÁ LA RELACIÓN DE EMPLEADOS:

Código SQL:

Mostrar la relación de empleados:

CREATE PROCEDURE QUERY17ASSELECT EmployeeID , LastName, FirstNameFROM Employees

Mostrar las órdenes realizadas por unempleado:

CREATE PROC QUERY17i@IDE INTASSELECT OrderID , OrderDate ,E.EmployeeIDFROM Employees AS E INNER JOINOrders AS O

ONE.EmployeeID = O.EmployeeIDWHERE E.EmployeeID = @IDE

Page 61: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 61

Código en Visual:

Imports System.Data.SqlClient

Public Class Form17

Private Sub Form17_Load(sender As System.Object, e As System.EventArgs) HandlesMyBase.Load

Dim datos As New SqlDataAdapter("QUERY17", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProceduredatos.Fill(ds, "QUERY17")dgv_cab.DataSource = ds.Tables(0)

End Sub

Private Sub dgv_cab_CellEnter(sender As Object, e AsSystem.Windows.Forms.DataGridViewCellEventArgs) Handles dgv_cab.CellEnter

Dim datos As New SqlDataAdapter("QUERY17i", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@IDE", SqlDbType.Int).Value =

dgv_cab.Rows(e.RowIndex).Cells(0).Valuedatos.Fill(ds, "QUERY17i")dgv_det.DataSource = ds.Tables(0)Label2.Text = dgv_cab.Rows(e.RowIndex).Cells(1).Value + " " +

dgv_cab.Rows(e.RowIndex).Cells(2).Value

End SubEnd Class

Nota: para poder ir a un nuevo datagried view a partir de uno debemos tener

en cuenta la siguiente sentencia:

Datagriedview1.Rows(valor).Cells(valor).Value

En donde:

Rows hace referencia a la fila.

Cells hace referencia a la columna.

Page 62: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 62

Page 63: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 63

Page 64: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 64

5. MOSTRAR LA RELACIÓN DE EMPLEADOS, LAS ÓRDENES QUE REALIZÓ UN

DETERMINADO EMPLEADO Y LOS PRODUCTOS DE DICHA ORDEN:

Código SQL:

Mostrar la relación de empleados:

CREATE PROCEDURE QUERY17ASSELECT EmployeeID , LastName , FirstNameFROM Employees

Mostrar las órdenes realizadas por un empleado:

CREATE PROC QUERY17i@IDE INTASSELECT OrderID , OrderDate , E.EmployeeIDFROM Employees AS E INNER JOIN Orders AS O

ON E.EmployeeID =O.EmployeeIDWHERE E.EmployeeID = @IDE

Mostrar los productos y detalles de dicha orden:

CREATE PROCEDURE QUERY17ii@iden intasselect o.orderid, p.productid, p.productname,p.unitprice, quantityfrom orders as o inner join [Order Details] as od

on o.orderid= od.orderidinner join products as pon od.productid =

p.productidwhere od.orderid= @iden

Page 65: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 65

Código en Visual:

Imports System.Data.SqlClientPublic Class Form18

Private Sub Form18_Load(sender As System.Object, e AsSystem.EventArgs) Handles MyBase.Load

Dim datos As New SqlDataAdapter("QUERY17", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType =

CommandType.StoredProceduredatos.Fill(ds, "QUERY17")dgv_cab.DataSource = ds.Tables(0)

End Sub

Private Sub dgv_cab_CellContentClick(sender As System.Object, eAs System.Windows.Forms.DataGridViewCellEventArgs) Handlesdgv_cab.CellContentClick

Dim datos As New SqlDataAdapter("QUERY17i", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType =

CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@IDE",

SqlDbType.Int).Value = dgv_cab.Rows(e.RowIndex).Cells(0).Valuedatos.Fill(ds, "QUERY17i")dgv_det.DataSource = ds.Tables(0)Label2.Text = dgv_cab.Rows(e.RowIndex).Cells(1).Value + " "

+ dgv_cab.Rows(e.RowIndex).Cells(2).ValueEnd Sub

Private Sub dgv_det_CellContentClick(sender As System.Object, eAs System.Windows.Forms.DataGridViewCellEventArgs) Handlesdgv_det.CellContentClick

Dim datos As New SqlDataAdapter("QUERY17ii", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType =

CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@iden",

SqlDbType.Int).Value = dgv_det.Rows(e.RowIndex).Cells(0).Valuedatos.Fill(ds, "QUERY17ii")DataGridView1.DataSource = ds.Tables(0)Label4.Text = dgv_det.Rows(e.RowIndex).Cells(0).Value

End Sub

Page 66: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 66

Page 67: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 67

Page 68: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 68

III. FORMULARIOS – HEREDADOS

Visual Studio 2010 nos permite crear formularios que hereden las

características que puede poseer otro formulario; a este tipo de

formularios se les denomina Formularios Heredados.

Para crear este tipo de formularios debemos seguir los siguientes pasos:

Crear el formulario plantilla con un diseño determinado:

Page 69: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 69

Clic derecho en el nombre del proyecto para poder agregar un nuevo

elemento; en el explorador de soluciones:

Page 70: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 70

Aparecerá la siguiente ventana; en ella debemos elegir la opción Windows

Form, en la opción “Elementos comunes”:

Tendremos las siguientes opciones a elegir; en este caso seleccionaremos

“Formulario Heredado:”

Page 71: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 71

Aparecerá la ventana “Selector de Herencia”; aquí debemos elegir de qué

formulario deseamos heredar las características (para el ejemplo será el

formulario renombrado anteriormente como “Plantilla”):

Finalmente, tenemos nuestro nuevo formulario Heredado:

Page 72: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 72

PRÁCTICA V

Crear una tabla en la base de datos Northwind llamada “Personas”, la tabla

debe contener los siguientes atributos y sus respectivos tipos de datos:

ATRIBUTO TIPO DE DATO REFERENCIA

Idperso (clave primaria) Char (8) Código

nomperso Varchar (30) Nombres

apeperso Varchar (40) Apellidos

email Varchar (50) Correo Electrónico

genero Char (1) Género

estadocivil Char (1) Estado civil

fechanac datetime Fecha de Nacimiento

1. LLENAR DATOS EN LA TABLA PERSONAS, MEDIANTE UNA VENTANA

HECHA EN VISUAL:

Código SQL:

Stored Procedure:

create procedure insertar@id char(10) ,@NOMBRE VARCHAR(30) ,@APELLIDOS VARCHAR(40) ,@CORREO VARCHAR(50) ,@GEN CHAR(1) ,@ESTCIV CHAR(1),@NAC DATETIMEasinsert into personasVALUES (@id, @NOMBRE,@APELLIDOS, @CORREO, @GEN , @ESTCIV,@NAC)SELECT *FROM personas

Page 73: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 73

Código en Visual:

Imports System.Data.SqlClientPublic Class Form19

Sub LIMPIAR_INGRESO() ' SUBPROGRAMA QUE VA A LIMPIAR TDAS LAS CAJAS'For Each objeto In Me.Controls' If TypeOf objeto Is TextBox Then' objeto.text = Space(0)' End If'Next

TextBox1.Text = ""TextBox2.Text = ""TextBox3.Text = ""TextBox4.Text = ""TextBox5.Text = ""TextBox6.Text = ""TextBox7.Text = ""TextBox1.Focus()

End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)Handles Button1.Click

Dim insert_per As New SqlCommand("insertar", conex)Dim respuesta As Integer ' si es 1 se ejecuta si es 2 no se ejecuta el

insert

insert_per.CommandType = CommandType.StoredProcedureinsert_per.Parameters.Add("@id", SqlDbType.Char, 8).Value =

TextBox1.Textinsert_per.Parameters.Add("@N", SqlDbType.VarChar, 30).Value =

TextBox2.Textinsert_per.Parameters.Add("@A", SqlDbType.VarChar, 40).Value =

TextBox3.Textinsert_per.Parameters.Add("@C", SqlDbType.VarChar, 50).Value =

TextBox4.Textinsert_per.Parameters.Add("@G", SqlDbType.Char, 1).Value =

TextBox5.Textinsert_per.Parameters.Add("@EC", SqlDbType.Char, 1).Value =

TextBox6.Textinsert_per.Parameters.Add("@FN", SqlDbType.DateTime).Value =

TextBox7.Textconex.Open()respuesta = insert_per.ExecuteNonQuery ' devuelve el numero de filas o

registros afectados.

If respuesta = 1 ThenMessageBox.Show("SE GRABÓ EL REGISTRO")LIMPIAR_INGRESO()

Page 74: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 74

Page 75: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 75

2. MODIFICAR EL MODO DE INGRESO DE LOS DATOS “GÉNERO” Y

“ESTADO CIVIL” DEL EJERCICIO 1:

En el caso de “Género” se deberá ingresar mediante un clic en una

opción de un Radiobutton.

Para “Estado Civil” se seleccionará de una lista desplegable la opción que

deseemos.

Código SQL:

Stored Procedure:

create procedure insertar

@id char(10) ,

@NOMBRE VARCHAR(30) ,

@APELLIDOS VARCHAR(40) ,

@CORREO VARCHAR(50) ,

@GEN CHAR(1) ,

@ESTCIV CHAR(1),

@NAC DATETIME

as

insert into personas

VALUES (@id, @NOMBRE,@APELLIDOS, @CORREO, @GEN

, @ESTCIV, @NAC)

SELECT *

FROM personas

Page 76: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 76

Código en Visual:

Imports System.Data.SqlClientPublic Class Form20

Sub LIMPIAR_INGRESO() ' SUBPROGRAMA QUE VA A LIMPIAR TDAS LAS CAJAS

TextBox1.Text = ""TextBox2.Text = ""TextBox3.Text = ""TextBox4.Text = ""TextBox7.Text = ""TextBox1.Focus()

End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) HandlesButton1.Click

Dim insert_per As New SqlCommand("insertar", conex)Dim respuesta As Integer ' si es 1 se ejecuta si es 2 no se ejecuta el insert

Dim genero As CharIf RadioButton1.Checked Then

genero = "F"Else

genero = "M"End If

Dim SC As IntegerDim ESTADO As Char

SC = ListBox1.SelectedIndex

Select Case SC

Case 0ESTADO = "S"

Case 1ESTADO = "C"

Case 2ESTADO = "V"

Case 3ESTADO = "D"

End Select

insert_per.CommandType = CommandType.StoredProcedureinsert_per.Parameters.Add("@id", SqlDbType.Char, 8).Value = TextBox1.Textinsert_per.Parameters.Add("@N", SqlDbType.VarChar, 30).Value = TextBox2.Textinsert_per.Parameters.Add("@A", SqlDbType.VarChar, 40).Value = TextBox3.Textinsert_per.Parameters.Add("@C", SqlDbType.VarChar, 50).Value = TextBox4.Textinsert_per.Parameters.Add("@G", SqlDbType.Char, 1).Value = generoinsert_per.Parameters.Add("@EC", SqlDbType.Char, 1).Value = ESTADOinsert_per.Parameters.Add("@FN", SqlDbType.DateTime).Value = TextBox7.Textconex.Open()respuesta = insert_per.ExecuteNonQueryIf respuesta = 1 Then

MessageBox.Show("SE GRABÓ EL REGISTRO")LIMPIAR_INGRESO()

End IfEnd Sub

End Class

Page 77: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 77

3. BORRAR TODOS LOS REGISTRO DE LA TABLA “PERSONAS” PARA

PODER MODIFICARLA, LA CLAVE PRINCIPAL IDPERSO, DEBERÁ SER UN

ENTERO AUTOINCREMENTABLE (SE INICIALIZA EN 1 Y EL INCREMENTO

ES UNA UNIDAD).

ATRIBUTO TIPO DE DATO REFERENCIA

Idperso (clave primaria) int Código

nomperso Varchar (30) Nombres

apeperso Varchar (40) Apellidos

email Varchar (50) Correo Electrónico

genero Char (1) Género

estadocivil Char (1) Estado civil

fechanac datetime Fecha de Nacimiento

Page 78: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 78

NOTA: Si al querer modificar algún atributo de alguna

tabla nos aparece un mensaje de error, debemos

desactivar la opción “Impedir guardar cambios que

requieran volver a crear tablas”.

Page 79: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 79

Para solucionar el inconveniente, antes descrito; seguiremos los

siguientes pasos:

Clic en el menú “Herramientas”, luego elegir la opción “Opciones”:

Aparecerá la siguiente ventana:

Page 80: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 80

Elegir la opción “Designers” y desactivar la opción “Impedir

cambios que requieran volver a crear tablas”:

4. INGRESAR REGISTROS EN LA NUEVA TABLA “PERSONAS”.

Código SQL:

Stored Procedure “INSERTAR” modificado:

alter procedure insertar@N VARCHAR(30) ,@A VARCHAR(40) ,@C VARCHAR(50) ,@G CHAR(1) ,@Ec CHAR(1),@FN DATETIMEasinsert into personas(nomperso, apeperso, email, genero, estadocivil, fechanac)VALUES (@N,@A, @C, @G , @EC, @FN)

Page 81: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 81

Código en Visual:

Imports System.Data.SqlClient

Public Class Form21

Sub LIMPIAR_INGRESO()TextBox2.Text = ""TextBox3.Text = ""TextBox4.Text = ""TextBox7.Text = ""

End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) HandlesButton1.Click

Dim insert_per As New SqlCommand("insertar", conex)Dim respuesta As IntegerDim SC As IntegerDim ESTADO As CharDim genero As Char

If RadioButton1.Checked Thengenero = "F"

Elsegenero = "M"

End If

SC = ListBox1.SelectedIndex

Select Case SC

Case 0ESTADO = "S"

Case 1ESTADO = "C"

Case 2ESTADO = "V"

Case 3ESTADO = "D"

End Select

insert_per.CommandType = CommandType.StoredProcedureinsert_per.Parameters.Add("@N", SqlDbType.VarChar, 30).Value = TextBox2.Textinsert_per.Parameters.Add("@A", SqlDbType.VarChar, 40).Value = TextBox3.Textinsert_per.Parameters.Add("@C", SqlDbType.VarChar, 50).Value = TextBox4.Textinsert_per.Parameters.Add("@G", SqlDbType.Char, 1).Value = generoinsert_per.Parameters.Add("@EC", SqlDbType.Char, 1).Value = ESTADOinsert_per.Parameters.Add("@FN", SqlDbType.DateTime).Value = TextBox7.Textconex.Open()respuesta = insert_per.ExecuteNonQuery conex.Close()

If respuesta = 1 ThenMessageBox.Show("SE GRABÓ EL REGISTRO")LIMPIAR_INGRESO()

End IfEnd Sub

End Class

Page 82: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 82

5. LLENAR REGISTROS DE LA TABLA PERSONAS Y MOSTRARLOS:

Código SQL:

alter procedure insertar@N VARCHAR(30) ,@A VARCHAR(40) ,@C VARCHAR(50) ,@G CHAR(1) ,@Ec CHAR(1),@FN DATETIMEasinsert into personas(nomperso, apeperso, email, genero, estadocivil, fechanac)VALUES (@N,@A, @C, @G , @EC, @FN)

Page 83: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 83

Código en Visual:

Imports System.Data.SqlClientublic Class Form22

Sub cargar_datos()Dim datos As New SqlDataAdapter("select * from personas", conex)Dim ds As New Data.DataSetdatos.Fill(ds, "prod1")DataGridView1.DataSource = ds.Tables(0)

End Sub

Sub LIMPIAR_INGRESO() ' SUBPROGRAMA QUE VA A LIMPIAR TDAS LAS CAJAS

TextBox2.Text = ""TextBox3.Text = ""TextBox4.Text = ""TextBox7.Text = ""

End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.ClickDim insert_per As New SqlCommand("insertar", conex)Dim respuesta As Integer ' si es 1 se ejecuta si es 2 no se ejecuta el insertDim SC As IntegerDim ESTADO As CharDim genero As Char

If RadioButton1.Checked Thengenero = "F"

Elsegenero = "M"

End If

SC = ListBox1.SelectedIndex

Select Case SC

Case 0ESTADO = "S"

Case 1ESTADO = "C"

Case 2ESTADO = "V"

Case 3ESTADO = "D"

End Select

insert_per.CommandType = CommandType.StoredProcedureinsert_per.Parameters.Add("@N", SqlDbType.VarChar, 30).Value = TextBox2.Textinsert_per.Parameters.Add("@A", SqlDbType.VarChar, 40).Value = TextBox3.Textinsert_per.Parameters.Add("@C", SqlDbType.VarChar, 50).Value = TextBox4.Textinsert_per.Parameters.Add("@G", SqlDbType.Char, 1).Value = generoinsert_per.Parameters.Add("@EC", SqlDbType.Char, 1).Value = ESTADOinsert_per.Parameters.Add("@FN", SqlDbType.DateTime).Value = TextBox7.Textconex.Open()respuesta = insert_per.ExecuteNonQuery ' devuelve el numero de filas o registros afectados.conex.Close()

If respuesta = 1 ThenMessageBox.Show("SE GRABÓ EL REGISTRO")LIMPIAR_INGRESO()cargar_datos()

End If

End Sub

End Class

Page 84: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 84

Page 85: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 85

6. CREAR LAS SIGUIENTES TABLAS:

“LIBROS”

“AUTOR”

“EDITORIAL”

*Llenar con datos las tablas “AUTOR” y “EDITORIAL”.

ATRIBUTO TIPO DE DATO REFERENCIA

IdLibro int Código

Titulo Varchar (30) Título del Libro

IdEditorial int Código de la Editorial

Edicion Char (10) Número de Edición

Año_Publicacion datetime Año de Publicación

IdAutor int Código del Autor

ATRIBUTO TIPO DE DATO REFERENCIA

IdAutor int Código

Nombre Varchar (50) Nombre del Autor

Fecha_Nac datetime Fecha de Nacimiento

Pais Char (10) País de Origen

ATRIBUTO TIPO DE DATO REFERENCIA

IdEditorial int Código

Nombre Varchar (50) Nombre de la Editorial

Pais VarChar (20) País en donde funciona

la Editorial

Page 86: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 86

CREAR UN FORMULARIO QUE PERMITA REGISTRAR LIBROS, SE

MOSTRARÁ LOS AUTORES Y LAS EDITORIALES EN LISTAS

DESPLEGABLES DE LAS QUE SE OBTENDRÁ EL CÓDIGO DE AUTOR Y

EDITORIAL RESPECTIVAMENTE:

Código SQL:

Código en Visual:

CREATE PROCEDURE libro@t VARCHAR(30,@edit int,@ed CHAR(10),@ap char (10), @idau intasinsert into libros(titulo, IDEDITORIAL, edicion, año_publicacion, IDAUTOR)VALUES (@t,@edit, @ed, @ap , @idau)

Imports System.Data.SqlClientPublic Class Form23

Sub LIMPIAR_INGRESO()

End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.ClickDim insert_per As New SqlCommand("libro", conex)Dim respuesta As Integer ' si es 1 se ejecuta si es 2 no se ejecuta el insert

insert_per.CommandType = CommandType.StoredProcedureinsert_per.Parameters.Add("@t", SqlDbType.VarChar, 30).Value = TextBox1.Textinsert_per.Parameters.Add("@ed", SqlDbType.Char, 10).Value = TextBox3.Textinsert_per.Parameters.Add("@ap", SqlDbType.Char, 10).Value = TextBox4.Textinsert_per.Parameters.Add("@edit", SqlDbType.Int).Value = ListBox1.SelectedValueinsert_per.Parameters.Add("@idau", SqlDbType.Int).Value = ListBox2.SelectedValueconex.Open()respuesta = insert_per.ExecuteNonQueryconex.Close()

If respuesta = 1 ThenMessageBox.Show("SE REGISTRÓ")LIMPIAR_INGRESO()

End If

End Sub

Private Sub Form23_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load'TODO: esta línea de código carga datos en la tabla 'PAIDataSet5.EDITORIAL' Puede moverla o quitarla

según sea necesario.Me.EDITORIALTableAdapter.Fill(Me.PAIDataSet5.EDITORIAL)'TODO: esta línea de código carga datos en la tabla 'PAIDataSet4.AUTOR' Puede moverla o quitarla según

sea necesario.Me.AUTORTableAdapter.Fill(Me.PAIDataSet4.AUTOR)

End SubEnd Class

Page 87: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 87

CONFIGURAMOS LA CONEXIÓN PARA LA LISTA DESPLEGABLE DE

AUTORES:

Clic en el triángulo desplegable de la esquina superior derecha del

listbox, aparecerá la siguiente ventana:

Clic en la opción “Agregar origen de datos del proyecto”:

Page 88: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 88

Clic en el botón “Siguiente”:

Page 89: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 89

Clic en el botón “Nueva conexión”:

Probamos la conexión:

Page 90: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 90

Se mostrará la siguiente pantalla:

Luego cargarán los datos y seleccionaremos sólo los que vamos a utilizar, en este

caso es la tabla “AUTOR” y de ella sólo necesitaremos los atributos “IdAutor y

Nombre”, luego clic en finalizar:

Page 91: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 91

Similar procedimiento se sigue para la conexión del listbox de “Editoriales”, con la

salvedad que se elige los datos de la tabla “Editoriales”.

Finalmente, las pantallas del nuevo programa:

Page 92: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 92

PRÁCTICA VI

1. MOSTRAR EN UN FORMULARIO INFORMACIÓN DE LAS CATEGORÍAS DE LA

BASE DE DATOS NORTHWIND; SE PERMITIRÁ AGREGAR OTRAS

CATEGORÍAS; MÁS NO ELIMINARLAS.

Creamos el origen de datos, esta ventana la podemos encontrar cerca

de la ventana herramientas o al presionar las siguiente combinación

Mayus+Alt+D:

Nota: Un Origen de

datos se crea para

todo el proyecto.

Page 93: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 93

Page 94: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 94

Page 95: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 95

Diseñamos el Formulario; para ello debemos seguir los siguientes pasos:

Page 96: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 96

Luego arrastramos la lista “Categorías” hacia el formulario; se mostrará lo

siguiente:

LOS NOMBRES DE LA CAJA DE TEXTO VARIAN DE ACUERDO AL TIPO DE DATO QUE

EN SU EJECUCIÓN CONTENDRÁ:

LA CAJA DE TEXTO QUE CORRESPONDE AL CÓDIGO DE CATEGORÍA

TIENE POR NOMBRE “CategoryIdTextBox”.

LA CAJA DE TEXTO QUE CORRESPONDE AL NOMBRE DE CATEGORÍA

TIENE POR NOMBRE “CategoryNameTextBox”.

LA CAJA DE TEXTO QUE CORRESPONDE A LA DESCRIPCOÓN TIENE

POR NOMBRE “DescriptionTextBox”.

La caja de texto que corresponde al Código de la Categoría será modificada,

pues es clave principal y nosotros no podemos modificarla; es entero

autoincrementable.

Modificamos la propiedad “READ ONLY”, por defecto el valor de esta

propiedad es “false”, la cambiamos a “true”.

Page 97: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 97

Para agregar una nueva categoría debemos hacer clic en el siguiente botón:

Escribiremos los datos que nos solicitan, y para guardar dicha información

debemos hacer clic en el botón:

Entonces tendremos una nueva categoría:

Page 98: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 98

2. MOSTRAR TODOS LOS PRODUCTOS DE UNA CATEGORÍA:

Agregaremos un nuevo origen de datos; similar al ejercicio

1; para el presente ejemplo elegiremos la tabla categorías.

El código visual que utilizaremos es el siguiente:

Imports System.Data.SqlClient

Public Class Form26

Sub cargar_datos()

Dim datos As New SqlDataAdapter("select productname, unitprice, unitsinstock, categoryidfrom products where categoryid=@cate", conex)

datos.SelectCommand.Parameters.Add("@cate", SqlDbType.Int).Value =CInt(CategoryIDTextBox.Text)

Dim ds As New Data.DataSet

datos.Fill(ds, "detalle")

DataGridView1.DataSource = ds.Tables("detalle")

End Sub

Private Sub CategoriesBindingNavigatorSaveItem_Click(sender As System.Object, e AsSystem.EventArgs)

Me.Validate()Me.CategoriesBindingSource.EndEdit()Me.TableAdapterManager.UpdateAll(Me.NorthwindDataSet11)

End Sub

Private Sub CategoriesBindingNavigatorSaveItem_Click_1(sender As System.Object, e AsSystem.EventArgs)

Me.Validate()Me.CategoriesBindingSource.EndEdit()Me.TableAdapterManager.UpdateAll(Me.NorthwindDataSet11)

End Sub

Private Sub Form26_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.LoadMe.CategoriesTableAdapter.Fill(Me.NorthwindDataSet11.Categories)cargar_datos()

End Sub

Private Sub BindingNavigatorMoveNextItem_Click(sender As System.Object, e As System.EventArgs)Handles BindingNavigatorMoveNextItem.Click, BindingNavigatorMoveLastItem.Click,BindingNavigatorMovePreviousItem.Click, BindingNavigatorMoveFirstItem.Click

cargar_datos()End Sub

Private Sub CategoryIDTextBox_TextChanged(sender As System.Object, e As System.EventArgs)Handles CategoryIDTextBox.TextChanged

cargar_datos()End Sub

Page 99: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 99

Page 100: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 100

Page 101: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 101

3. MOSTRAR LOS DETALLES DE UN PRODUCTO INGRESADO (CÓDIGO DEL PRODUCTO)

POR TECLADO (NO UTILIZAR STORED PROCEDURE):

Código Visual:

Imports System.Data.SqlClientPublic Class Form27

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

Dim comando As New SqlCommand("select productname, unitprice, unitsinstock, categoryid fromproducts where productid= @id", conex)

comando.Parameters.Add("@id", SqlDbType.Int).Value = CInt(TextBox1.Text)

Dim registro As SqlDataReader

conex.Open()

registro = comando.ExecuteReader() ' se utiliza cuando es una consulta el executereadertrae una variable y la alamcena en registro

registro.Read()

If registro.HasRows = True Then ' utilizado para contar el número de filas (registros)existentes

TextBox2.Text = registro.Item(0) ' referencia al primer campo que se desea mostrar(productname)

TextBox3.Text = registro.Item(1) ' referencia al segundo campo que se desea mostrar(unitprice)

TextBox4.Text = registro.Item(2) ' referencia al tercer campo que se desea mostrar(unitsinstock)

TextBox5.Text = registro.Item(3) ' referencia al cuarto campo que se desea mostrar(categoryid)

ElseMessageBox.Show("¡NO EXISTE ESTE PRODUCTO!")

End Ifregistro.Close()conex.Close()

End Sub

End Class

Page 102: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 102

Page 103: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 103

Page 104: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 104

4. MOSTRAR EN UN MENSAJE EL NOMBRE DEL PRODUCTO, PRECIO Y STOCK

DE LOS PRODUCTOS DE UN DETERMINADO PROVEEDOR (NO USAR STORED

PROCEDURE, EL CÓDIGO DEL PROVEEDOR SERÁ INGRESADO POR

TECLADO):

Código Visual:

Imports System.Data.SqlClient

Public Class Form28

Private Sub Button1_Click(sender As System.Object, e AsSystem.EventArgs) Handles Button1.Click

Dim comando As New SqlCommand("select productname,unitprice, unitsinstock from products where supplierid= @id",conex)

comando.Parameters.Add("@id", SqlDbType.Int).Value =CInt(TextBox1.Text)

Dim registro As SqlDataReader

conex.Open()

registro = comando.ExecuteReader()

Do While registro.Read()

MessageBox.Show(registro.Item(0) + " - " +CStr(registro.Item(1)) + " - " + CStr(registro.Item(2)))

Loop

registro.Close()conex.Close()

End Sub

Page 105: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 105

Page 106: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 106

5. MOSTRAR LOS PRODUCTOS DE UN PROVEEDOR EN UNA LISTA; EL CÓDIGO

DEL PROVEEDOR SERÁ INGRESADO POR TECLADO (NO UTILIZAR STORED

PROCEDURE):

Código Visual:

Imports System.Data.SqlClientPublic Class Form29

Private Sub Button1_Click(sender As System.Object, e AsSystem.EventArgs) Handles Button1.Click

Dim comando As New SqlCommand("select productname,unitprice, unitsinstock from products where supplierid= @id",conex)

comando.Parameters.Add("@id", SqlDbType.Int).Value =CInt(TextBox1.Text)

Dim registro As SqlDataReader

conex.Open()

registro = comando.ExecuteReader()

Do While registro.Read()

ListBox1.Items.Add(registro.Item(0) + " - " +CStr(registro.Item(1)) + " - " + CStr(registro.Item(2)))

Loop

registro.Close()conex.Close()

End Sub

End Class

Page 107: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 107

Page 108: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 108

6. CREAR UN FORMULARIO QUE PERMITA INGRESAR UN USUARIO Y SU

CLAVE:

Para resolver este ejercicio necesitamos un formulario especial, denominado

“Formulario de Inicio de Sesión”.

Para obtener este formulario debemos seguir los siguientes pasos:

Clic derecho sobre el nombre del proyecto, en el Explorador de

Soluciones, para poder agregar un nuevo formulario:

Nos aparece la siguiente ventana; elegimos la opción “Windows Form”, se

muestran las siguientes opciones:

Page 109: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 109

Elegimos la opción “Formulario de Inicio de Sesión”:

Código Visual:

Imports System.Data.SqlClient

Public Class LoginForm30

Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click

Dim QUERY As New SqlCommand("SELECT COUNT(*) FROM USUARIO WHERE IDUSUARIO= @U AND PASSWORD = @P",conex)

QUERY.Parameters.Add("@U", SqlDbType.VarChar, 20).Value = UsernameTextBox.TextQUERY.Parameters.Add("@P", SqlDbType.VarChar, 20).Value = PasswordTextBox.Textconex.Open()

Dim VALOR As Integer

VALOR = QUERY.ExecuteScalar ' ES UN SÓLO VALOR

conex.Close()

If VALOR = 1 ThenForm1.Show()Me.Hide()

ElseMessageBox.Show("Usuario y/o Clave incorrectas")UsernameTextBox.Text = " "PasswordTextBox.Text = " "UsernameTextBox.Focus()

End If

End Sub

Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesCancel.Click

Me.Close()End Sub

End Class

Page 110: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 110

Page 111: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 111

7. PERMITIR CAMBIAR DE CLAVE AL USUARIO EN OTRO FORMULARIO:

Código Visual:

Imports System.Data.SqlClient

Public Class Form31

Private Sub Button1_Click(sender As System.Object, e AsSystem.EventArgs) Handles Button1.Click

If TextBox3.Text = TextBox4.Text Then

Dim comando As New SqlCommand("update usuario set password =@NUEVAC where IDusuario = @USER and password=@CA", conex)

comando.Parameters.Add("@NUEVAC", SqlDbType.VarChar,20).Value = TextBox3.Text

comando.Parameters.Add("@USER", SqlDbType.VarChar, 20).Value= TextBox1.Text

comando.Parameters.Add("@CA", SqlDbType.VarChar, 20).Value =TextBox2.Text

conex.Open()comando.ExecuteNonQuery()

conex.Close()

End If

End Sub

End Class

Page 112: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 112

IV. REPORTING SERVICES: Visual Studio nos permite crear reportes con

datos tomados de una base de datos.

Los reportes son consultas que deben ser plasmadas en un documento

para su lectura, comprensión e interpretación.

Para agregar un informe, en Visual Studio 2010 debemos seguir los

siguientes pasos:

Clic derecho sobre el nombre del proyecto (Explorador de

Soluciones) y agregar un nuevo elemento:

Page 113: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 113

Clic en la opción “Reporting” y elegir “Informe”:

Finalmente la ventana para desarrollar le informe está creada:

Page 114: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 114

Una vez creado el informe; debemos crear su origen de datos; es

decir de dónde deseamos obtener la información:

Clic en la pestaña “Nuevo” y elegir “Nuevo Origen de Datos”:

Se mostrará la ventana “Propiedades del Conjunto de Datos”, clic

en el botón “Nuevo”:

Page 115: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 115

Aparece la ventana “Asistente para la Configuración de Datos”, clic

en “Siguiente”:

Page 116: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 116

Clic en el botón “Nueva Conexión”

Page 117: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 117

En esta ventana escribimos el nombre del servidos y la base de

datos a la que deseamos conectarnos:

Probamos la conexión:

Page 118: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 118

La siguiente ventana demuestra que está cargando los datos para

poder escoger el correcto:

Elegimos el procedimiento almacenado correcto:

Page 119: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 119

Podemos observar el entorno de dearrollo de un Informe; aquí

podemos usar algunas herramientas para mostrar la información:

Page 120: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 120

Page 121: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 121

Debemos crear un nuevo formulario, en este incluiremos el reporte,

mediante la herramienta “Reporte Viewer”

Page 122: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 122

La vista del informe:

Page 123: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 123

Podemos exportar el informe a Excel, PDF o Word:

Elegimos la ruta e, donde deseamos guardar el informe:

Page 124: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 124

Ahora podemos visualizar el informe desde Ms. Word:

Page 125: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 125

PRÁCTICA VII

1. MOSTRAR LAS ÓRDENES REALIZADAS POR UN EMPLEADO:

Código SQL:

Código en Visual:

create procedure sp1@id intasselect e.employeeid, orderid, orderdate, customeridfrom Employees as e inner join Orders as oon e.EmployeeID = o.EmployeeIDwhere e.EmployeeID = @id

Imports System.Data.SqlClient

Public Class Form1

Private Sub EmployeesBindingNavigatorSaveItem_Click(sender As System.Object, e AsSystem.EventArgs) Handles EmployeesBindingNavigatorSaveItem.Click

Me.Validate()Me.EmployeesBindingSource.EndEdit()Me.TableAdapterManager.UpdateAll(Me.NorthwindDataSet)

End Sub

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) HandlesMyBase.Load

Me.EmployeesTableAdapter.Fill(Me.NorthwindDataSet.Employees)

End Sub

Private Sub TabPage2_Click(sender As System.Object, e As System.EventArgs) HandlesTabPage2.Click

End Sub

Private Sub EmployeeIDTextBox_TextChanged(sender As System.Object, e AsSystem.EventArgs) Handles EmployeeIDTextBox.TextChanged

Dim datos As New SqlDataAdapter("sp1", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value =

EmployeeIDTextBox.Textdatos.Fill(ds, "s")DataGridView1.DataSource = ds.Tables(0)

End Sub

End Class

Page 126: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 126

Page 127: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 127

2. MOSTRAR EL TOTAL DE ÓRDENES REALIZADAS POR UN EMPLEADO:

Código SQL:

Código Visual:

create procedure sp2@y intasselect distinct companyname, YEAR(orderdate) as año,COUNT(*) as totalfrom Customers as c inner join orders as o on c.CustomerID= o.CustomerIDgroup by CompanyName , YEAR(OrderDate)having year(orderdate)=@y

Public Class Form2

Private Sub Form2_Load(ByVal sender As System.Object, ByVal eAs System.EventArgs) Handles MyBase.Load

Me.sp2TableAdapter.Fill(Me.PAIDataSet.sp2, 1996)Me.ReportViewer1.RefreshReport()

End Sub

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender AsSystem.Object, ByVal e As System.EventArgs) HandlesComboBox1.SelectedIndexChanged

Me.sp2TableAdapter.Fill(Me.PAIDataSet.sp2,ComboBox1.SelectedValue)

Me.ReportViewer1.RefreshReport()End Sub

Private Sub ReportViewer1_Load(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles ReportViewer1.Load

End Sub

Private Sub ComboBox1_SelectedValueChanged(ByVal sender AsObject, ByVal e As System.EventArgs) HandlesComboBox1.SelectedValueChanged

Me.sp2TableAdapter.Fill(Me.PAIDataSet.sp2,ComboBox1.SelectedValue)

Me.ReportViewer1.RefreshReport()End Sub

Page 128: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 128

Page 129: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 129

CREAR UN SISTEMA DE CONTROL DE ASISTENCIA PARA LA XII-

SEMANA SISTÉMICA

1. FORMULARIOS:

MANTENIMIENTO DE INSTITUCIONES EDUCATIVAS:

MANTENIMIENTO DE CONFERENCIAS:

Page 130: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 130

INGRESAR UN NUEVO PARTICIPANTE:

CÓDIGO SQL:

create procedure insertar@id char(10) ,@ap VARCHAR(25) ,@am VARCHAR(25) ,@n VARCHAR(25) ,@e CHAR(45) ,@s CHAR(1),@ii intasinsert into PARTICIPANTESVALUES (@id, @ap ,@am, @n, @e , @s, @ii)

Page 131: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 131

Código Visual:

Imports System.Data.SqlClient

Public Class NUEVOS_PARTICIPANTES

Private Sub NUEVOS_PARTICIPANTES_Load(sender As System.Object, e As System.EventArgs) HandlesMyBase.Load

Me.INSTITUCIONESTableAdapter.Fill(Me.SEMANASISTEMICADataSet2.INSTITUCIONES)

End Sub

Sub LIMPIAR_INGRESO()

TextBox1.Text = ""TextBox2.Text = ""TextBox3.Text = ""TextBox4.Text = ""TextBox5.Text = ""TextBox1.Focus()

End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.ClickDim datos As New SqlCommand("insertar", conex)Dim respuesta As IntegerDim genero As IntegerIf RadioButton1.Checked Then

genero = 1Else

genero = 2End If

datos.CommandType = CommandType.StoredProceduredatos.Parameters.Add("@id", SqlDbType.Char, 10).Value = TextBox1.Textdatos.Parameters.Add("@ap", SqlDbType.VarChar, 25).Value = TextBox2.Textdatos.Parameters.Add("@am", SqlDbType.VarChar, 25).Value = TextBox3.Textdatos.Parameters.Add("@n", SqlDbType.VarChar, 25).Value = TextBox4.Textdatos.Parameters.Add("@e", SqlDbType.Char, 45).Value = TextBox5.Textdatos.Parameters.Add("@s", SqlDbType.Char, 1).Value = generodatos.Parameters.Add("@ii", SqlDbType.Int).Value = ComboBox1.SelectedValue

conex.Open()

respuesta = datos.ExecuteNonQuery

If respuesta = 1 ThenMessageBox.Show("SE GRABÓ EL REGISTRO")LIMPIAR_INGRESO()

End IfDim dat As New SqlDataAdapter("ver", conex)Dim ds As New Data.DataSetdat.SelectCommand.CommandType = CommandType.StoredProceduredat.Fill(ds, "ver")DataGridView1.DataSource = ds.Tables(0)

End Sub

Private Sub LinkLabel1_LinkClicked(sender As System.Object, e AsSystem.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked

Buscar_Participantes.Show()End Sub

Page 132: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 132

BUSCAR UN PARTICIPANTE:

Page 133: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 133

Código SQL:

Código en Visual:

Imports System.Data.SqlClient

Public Class Buscar_Participantes

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e AsSystem.EventArgs) Handles TextBox1.TextChanged

If RadioButton1.Checked Then

Dim datos As New SqlCommand("cod", conex)datos.CommandType = CommandType.StoredProcedureDim dat As New SqlDataAdapter("cod", conex)Dim ds As New Data.DataSetdat.SelectCommand.CommandType = CommandType.StoredProceduredat.SelectCommand.Parameters.Add("@id", SqlDbType.VarChar, 20).Value =

TextBox1.Textdat.Fill(ds, "T")DataGridView1.DataSource = ds.Tables(0)

ElseDim datos As New SqlCommand("apepaternito", conex)datos.CommandType = CommandType.StoredProcedureDim dat As New SqlDataAdapter("apepaternito", conex)Dim ds As New Data.DataSetdat.SelectCommand.CommandType = CommandType.StoredProceduredat.SelectCommand.Parameters.Add("@a", SqlDbType.VarChar, 25).Value = TextBox1.Textdat.Fill(ds, "T")DataGridView1.DataSource = ds.Tables(0)

End IfEnd Sub

Búsqueda por código:

create procedure cod@id varchar(20)asselect *from PARTICIPANTESwhere IdParticipante like @id+'%'

Búsqueda por apellido:

create procedure apepaternito@a varchar(25)asselect *from PARTICIPANTESwhere apepat like @a+'%'

Page 134: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 134

REGISTRAR ASISTENTES:

Page 135: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 135

Código SQL:

Stored procedure para registrar un asistente:

create procedure reg@f datetime ,@idp VARCHAR(10) ,@idc intasinsert into ASISTENCIAVALUES (@f, @idp ,@idc)

Stored procedure para buscar a un participante yregistrarlo:

create procedure rr@text varchar (25)asselectIdParticipante,ApePat,ApeMat,Nombresfrom PARTICIPANTESwhere ApePat like @text

Page 136: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 136

Código en Visual:

Imports System.Data.SqlClientPublic Class Asistencia

Private Sub Asistencia_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

Me.CONFERENCIASTableAdapter.Fill(Me.SEMANASISTEMICADataSet3.CONFERENCIAS)End Sub

Sub registrar()Dim insert_per As New SqlCommand("reg", conex)Dim respuesta As Integerinsert_per.CommandType = CommandType.StoredProcedureinsert_per.Parameters.Add("@f", SqlDbType.DateTime).Value = DateTime.Nowinsert_per.Parameters.Add("@idp", SqlDbType.VarChar, 10).Value = TextBox1.Textinsert_per.Parameters.Add("@idc", SqlDbType.Int).Value = ComboBox1.SelectedValueconex.Open()respuesta = insert_per.ExecuteNonQueryconex.Close()

If respuesta = 1 ThenMessageBox.Show("SE GRABÓ EL REGISTRO")

End IfDim datos As New SqlDataAdapter("v", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@i", SqlDbType.Int).Value = ComboBox1.SelectedValuedatos.Fill(ds, "i")DataGridView1.DataSource = ds.Tables(0)

End SubPrivate Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs)

Handles TextBox1.KeyPressIf e.KeyChar = ChrW(13) Then

registrar()End If

End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) HandlesComboBox1.SelectedIndexChanged

Label4.Text = CStr(ComboBox1.Text)End Sub

Private Sub TextBox2_TextChanged(sender As System.Object, e As System.EventArgs) HandlesTextBox2.TextChanged

Dim datos As New SqlDataAdapter("rr", conex)Dim ds As New Data.DataSetdatos.SelectCommand.CommandType = CommandType.StoredProceduredatos.SelectCommand.Parameters.Add("@text", SqlDbType.VarChar, 25).Value = TextBox2.Textdatos.Fill(ds, "i")DataGridView2.DataSource = ds.Tables(0)

End Sub

Private Sub DataGridView2_CellContentClick(sender As System.Object, e AsSystem.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick

TextBox1.Text = DataGridView2.Rows(e.RowIndex).Cells(0).ValueEnd Sub

End Class

Page 137: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 137

REPORTE DE ALUMNOS PARTICIPANTES, ORDENADOS ALFABÉTICAMENTE:

Page 138: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 138

Código SQL:

REPORTE DE CONFERENCIAS DICTADAS:

Código SQL:

alter procedure asistasselect IdParticipante, ApePat+' '+ApeMat+''+Nombres as Nombre, Email,IdInstifrom PARTICIPANTESorder by ApePat+ApeMat+Nombres

create proc confasselect *from CONFERENCIASorder by NombreConfe

Page 139: Visual 2010 sql server 2008

Universidad Nacional de Cajamarca MANUAL DE PROGRAMACIÓN APLICADA I

S A L A Z A R C A C H O , I r i s N o h e l y Página 139

REPORTE DE ASISTENTES POR CONFERENCIA:

Código SQL:

CREATE PROCEDURE PARTCONF@IDC INTASSELECT P.IdParticipante,ApePat+' '+ApeMat+''+Nombres as NombreFROM PARTICIPANTES AS P INNER JOIN ASISTENCIAAS AON P.IdParticipante = A.IdParticipanteINNER JOIN CONFERENCIAS AS CON A.IdConfe = C.IdConfewhere C.IdConfe = @IDC