Sunday, September 5, 2010

Java call SQL Server stored procedure example

Recently made a small Java program (the first to write Java project oh), to the online search for a long time to find a better point of calling a stored procedure example, and are commonly used online setXXX ((int parameterIndex, XXX x) form. This form of feeling is not very intuitive, following the release of a complete used setXXX (String parameterName, XXX x) the preparation method. create a data table, stored procedure code is a complete release.

Create table:





CREATE   TABLE   [BookUser] ( 
[UserID]   [Int]   IDENTITY (1, 1) NOT   NULL, 
[UserName]   [Varchar] (50) COLLATE Chinese_PRC_CI_AS NOT   NULL, 
[Title]   [Nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT   NULL, 
[Guid]   [Uniqueidentifier]   NOT   NULL   CONSTRAINT   [DF_BookUser_Guid]   DEFAULT(newid ()), 
[BirthDate]   [Datetime]   NOT   NULL, 
[Description]   [Ntext] COLLATE Chinese_PRC_CI_AS NOT   NULL, 
[Photo]   [Image]   NULL, 
[Other]   [Varchar] (50) COLLATE Chinese_PRC_CI_AS NULL   CONSTRAINT 
[DF_BookUser_Other]   DEFAULT ('default'), 
CONSTRAINT   [PK_BookUser]   PRIMARY   KEY    CLUSTERED 
( 
[UserID] 
) ON   [PRIMARY] 
) ON   [PRIMARY] TEXTIMAGE_ON [PRIMARY] 
GO 

Create a stored procedure: 

CREATE   PROCEDURE InsertUser 
@ UserName   varchar (50), 
@ Title   varchar (255), 
@ Guid    uniqueidentifier, 
@ BirthDate   DateTime, 
@ Description   ntext, 
@ Photo   image, 
@ Other   nvarchar (50), 
@ UserID   int output 
As 
Set NOCOUNT ON 
If   Exists (select UserID from BookUser Where UserName =   UserName) 
RETURN   0 
ELSE 
Begin 
INSERT   INTO BookUser (UserName, Title, Guid, BirthDate, Description, Photo, Other) VALUES (@UserName, @ Title, @ Guid, @ BirthDate, @ Description, @ Photo, @ Other) 
SET   @ UserID   =   @ @ IDENTITY 
RETURN   1 
End 
GO 

No comments:

Post a Comment