存储过程

例子:

Create procedure GetAvgPbiaodi

@name varchar(10),@avgpbiaodi int output

As 

Declare @ErrorSave int

Set @ErrorSave=0

Select @avgpbiaodi=AVG(项目标的) from project as p inner join pmanager as pm

on p.负责人ID=pm.负责人ID where pm.姓名=@name

if(@@Error<>0)

Set @ErrorSave=@@Error

Return @ErrorSave

go

执行存储过程:

Declare @returnvalue int,@avg int

EXEC @returnvalue=GetAvgPbiaodi'李中新',@avg output

print'执行结果:'

print'返回值='+cast(@returnvalue as char(2))

print'李中新复杂项目的平均标的为:'+cast(@avg as char(10))

go

例子2:

create proc MyReturn

@t1 smallint,@t2 smallint,@retval smallint

As select @retval=@t1+@t2

Return @retval

调用:

Declare @myReturnValue smallint

Exec @myReturnValue=myReturn 9,9,0

Select'The eturn value is',@myReturnvalue

创建存储过程组:

Create Proc group_sp;1

As select * from authors

go

create proc guoup_sp;2

As select au_lname from authors

go

create proc group_sp;3

As select distinct city from authors

go

执行单个过程:exec group_sp;3 

if @RequiredCourseCredit is null

begin

set @RequiredCourseCredit=0

end 

一个完整的例子:

if exists(select * from sysobjects where name='usp_User_Summary' )

drop proc usp_User_Summary

go

create proc usp_User_Summary

 (

  @User_Id varchar(50)

)

as

declare @TotalCredit decimal(10,2) --总学分

declare @CourseCredit Decimal(10,2) --课程获得总学分

declare @CourseExtraCredit decimal(10,2) ---课程附加学分

declare @RequiredCourseCredit decimal(10,2) --必修课获得学分

declare @ExamCredit decimal(10,2) --考试获得学分

declare @CreditRange int --学分排名

declare @UserName varchar(50)--学员姓名 

declare @UserBussinessName varchar(50)---学员职位

declare @LoginTimes int --登录次数

declare @NeededCredit int --规定学分

declare @defaultCreditHour int --规定学分

declare @User_Nm int 

select @User_Nm=user_nm,@UserName=user_name,@LoginTimes=login_times,@NeededCredit=need_score,@defaultCreditHour = default_credit_hour from users  where user_id=@user_id

select @UserBussinessName= USER_BUSINESS_name from users a,USER_BUSINESS_MAIN b where a.USER_BUSINESS_nM=b.USER_BUSINESS_NM

select @ExamCredit =sum(USER_CREDIT_HOUR) from  Chw_Exam_Pref where user_id= @User_Id 

select @CourseCredit = sum(credit_hour),@CourseExtraCredit=sum(Extra_credit) from user_course_reg  where user_nm=@user_nm 

select @RequiredCourseCredit= sum(credit_hour) from user_course_reg  

where user_nm=@user_nm and Course_Id in(select Course_Id from CourseWare where Auto_Reg=0)

if @ExamCredit is null

begin

set @ExamCredit=0

end 

if @CourseCredit is null

begin

set @CourseCredit=0

end 

if @CourseExtraCredit is null

begin

set @CourseExtraCredit=0 

end 

if @RequiredCourseCredit is null

begin

set @RequiredCourseCredit=0

end  

create table #TempCreditRange

 (

   RangeId int identity(1,1),

   User_nm varchar(50) 

  )

 insert into #tempCreditRange (User_nm)

 select user_nm

    --sum(credit_hour) as credit_hour 

     from user_course_reg 

    group by user_nm 

order by sum(credit_hour) desc

 select @CreditRange =rangeId from #tempCreditRange 

where user_nm=@user_nm

select @ExamCredit+@CourseCredit as TotalCredit, 

@CourseCredit as CourseCredit,

@RequiredCourseCredit as RequiredCredit,

@CourseCredit-@RequiredCourseCredit as ElectiveCredit,

@ExamCredit as ExamCredit,

@CreditRange as CreditRange,

@UserBussinessName as UserBussinessName,

@UserName as UserName,

@LoginTimes as LoginTimes,

@NeededCredit as NeededCredit,

@defaultCreditHour as DefaultCreditHour

go 

课程学分+考试学分:

SET QUOTED_IDENTIFIER ON 

GO

SET ANSI_NULLS ON 

GO 

ALTER   proc [dbo].[allscore_new]

as

delete  from user_score_value insert into user_score_value(course_score,exam_score,user_nm,user_id,user_name,TotalCredit) select isnull(m.xf,0) as course_score , isnull(n.score1,0) as exam_score,m.user_nm,m.user_id,m.user_name,isnull(m.xf,0)+isnull(n.score1,0) as allscore from (select  isnull(sum(a.credit_hour),0)+isnull(sum(a.extra_credit),0) as xf,b.user_nm ,b.user_id,b.user_name from user_course_reg a,users b where a.user_nm=b.user_nm group by b.user_nm,b.user_id,b.user_name)m   left outer join   (select isnull(sum(a.user_credit_hour),0) as score1 ,b.user_nm user_nm ,b.user_id  user_id from chw_exam_pref a ,users  b  where a.user_id=b.user_id group by b.user_nm ,b.user_id)n on  m.user_nm=n.user_nm 

GO

SET QUOTED_IDENTIFIER OFF 

GO

SET ANSI_NULLS ON 

GO

sql存储过程top参数:

create procedure sel_getuser 

@top int 

as 

set rowcount @top 

select * from users 

set rowcount 0 

go  

如果没有行可以修改,则插入数据

begin tran
-- Update the row if it exists.
UPDATE AccountTranslation
SET Description = @TextValue
WHERE ID = @IdValue
AND
Language = @TranslateLanguage
-- Insert the row if the UPDATE statement failed.
IF (@@ROWCOUNT = 0 )
BEGIN
INSERT INTO AccountTranslation (ID, [Language], Description, IsSynchronized)
VALUES (@IdValue, @TranslateLanguage, @TextValue, @IsSynchronized)
END
commit tran

 存储过程中用到临时表和sql语句的字符串

USE [WASPPS]
GO
/****** Object: StoredProcedure [dbo].[insertMissingTranslationsForTable] Script Date: 05/12/2013 15:35:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[insertMissingTranslationsForTable]
(
@tableName NVARCHAR(128),
@IDsTable IdType READONLY,
@sourceLanguage NVARCHAR(5) = 'xx-XX'
)
AS
BEGIN
-- ---
--BEGIN TRANSACTION
--BEGIN TRY
SET NOCOUNT ON
-- ---
-- ---
DECLARE @translationTableName NVARCHAR(128)
DECLARE @sql NVARCHAR(4000)
DECLARE @missingRowCount INT
--DECLARE @existingRowCount INT = 0
DECLARE @rowsInserted INT
-- ---
SET @tableName = REPLACE(@tableName, '''', '''''') -- injection protection
IF @tableName = '_dynamicText'
BEGIN
SET @translationTableName = @tableName
END
ELSE
BEGIN
SET @translationTableName = @tableName + 'Translation'
END

SET @sourceLanguage = REPLACE(@sourceLanguage, '''', '''''') -- injection protection
PRINT '----------'
PRINT 'table [' + @tableName + '] tx [' + @translationTableName + '] source [' + @sourceLanguage + '] []'
-- ---------------------------------------------------------------------------
-- Remember the Id and Language of rows that we need to fill by taking a copy of an existing row.
-- This is a #table not a @table because we use it in dynamic sql later on.
-- ---------------------------------------------------------------------------
CREATE TABLE #missingRows (Id VARCHAR(512) NOT NULL, [Language] NVARCHAR(5) NOT NULL, LangTag NVARCHAR(5) NOT NULL, PRIMARY KEY (Id, Language))
-- ---
SET @sql = N'INSERT INTO #missingRows (Id, Language, LangTag)
SELECT X.Id, L.Id AS LanguageCode, ''?'' + SUBSTRING(L.Id, 1, 2) + ''-''
FROM ' + @tableName + ' X
JOIN @IDsTable ID ON X.Id = ID.Id
CROSS JOIN [Language] L
WHERE NOT EXISTS (SELECT NULL FROM ' + @translationTableName + ' XT WHERE XT.Id = X.Id AND XT.Language = L.id)
AND EXISTS (SELECT NULL FROM ' + @translationTableName + ' ST WHERE ST.Id = X.Id AND ST.language = ''' + @sourceLanguage + ''')
GROUP BY X.Id, L.Id, ''?'' + SUBSTRING(L.Id, 1, 2) + ''-'''
-- ---
--PRINT @sql
EXEC sp_executesql @sql, N'@IDsTable IdType READONLY', @IDsTable


--SELECT * FROM #missingRows
SELECT @missingRowCount = COUNT(*) FROM #missingRows
PRINT 'missing [' + CAST(@missingRowCount AS VARCHAR) + '] rows'
IF (@missingRowCount > 0)
BEGIN
-- ---------------------------------------------------------------------------
-- --- Count the number of translations that already exist for the changed ID's
-- ---------------------------------------------------------------------------
CREATE TABLE #existingRows (Id VARCHAR(512) NOT NULL, RecordCount INT NOT NULL, PRIMARY KEY (Id))
SET @sql = N'INSERT INTO #existingRows (Id, RecordCount)
SELECT X.Id, COUNT(X.Id)
FROM ' + @translationTableName + ' X
JOIN @IDsTable ID ON X.Id = ID.Id
GROUP BY X.Id'
--PRINT @sql
EXEC sp_executesql @sql, N'@IDsTable IdType READONLY', @IDsTable
-- ---

-- ---------------------------------------------------------------------------
-- --- Build strings of columns that we will insert into / select from
-- --- Certain columns are NOT to be translated and those are listed here.
-- ---
-- ---------------------------------------------------------------------------
DECLARE @colTbl TABLE (rowId INT NOT NULL IDENTITY(1,1), columnName NVARCHAR(128), maxLen INT NULL, appendQ TINYINT NOT NULL, PRIMARY KEY (rowId))
-- ---
INSERT INTO @colTbl (columnName, maxLen, appendQ)
SELECT column_name, character_maximum_length,
CASE WHEN data_type = 'nvarchar' AND (character_maximum_length >= 100 OR character_maximum_length = -1)
AND column_name NOT IN ('OwnerUserId', 'UserName', 'UserId', 'OwnerUserId', 'AssessingUserName',
'CompletedById', 'TargetAttractionRationale', 'ResourceFileName', 'ResourceURL')
THEN 1 ELSE 0 END -- this case value indicates to only append ?xx- to certain columns, not these ones listed
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = @translationTableName
AND column_name NOT IN ('Language', 'Id', 'tVersion')
ORDER BY ordinal_position
-- ---
SET @rowsInserted = @@ROWCOUNT
PRINT 'tx table [' + CAST(@rowsInserted AS VARCHAR) + '] columns'
--SELECT * FROM @colTbl
--SELECT columnName, appendQ, CAST(maxLen AS VARCHAR) AS ml FROM @colTbl
-- ---
DECLARE @into NVARCHAR(4000)
DECLARE @vals NVARCHAR(4000)
DECLARE @colName NVARCHAR(128)
DECLARE @appendQ TINYINT
DECLARE @colLen NVARCHAR(20) -- for nvarchar columns, this is the column size number converted to nvarchar
DECLARE @minRow INT
DECLARE @maxRow INT
SELECT @minRow = MIN(rowId), @maxRow = MAX(rowId) FROM @colTbl
WHILE (@minRow <= @maxRow)
BEGIN
SELECT @colName = columnName, @appendQ = appendQ, @colLen = CAST(CASE WHEN maxLen = -1 THEN 4000 ELSE maxLen END AS VARCHAR) FROM @colTbl WHERE rowId = @minRow
SET @into = ISNULL(@into + ', ', '') + '[' + @colName + ']' -- SQUARE BRACES IS FIX FOR 'OPTIONS' COLUMN WHICH IS A RESERVED WORD
-- where we add a prefix to the data in a column, ensure it does not exceed the max length of that column
SET @vals = ISNULL(@vals + ', ', '') + CASE WHEN @appendQ = 1 THEN 'SUBSTRING(MR.LangTag + [' + @colName + '], 1, ' + @colLen + ')' ELSE @colName END
SET @minRow = @minRow + 1
END
PRINT 'into [' + ISNULL(@into, '?NULL?') + ']'
PRINT 'vals [' + ISNULL(@vals, '?NULL?') + ']'
-- ---------------------------------------------------------------------------
-- --- Insert the missing rows
-- ---------------------------------------------------------------------------
SET @sql = N'INSERT INTO ' + @translationTableName + ' (Id, Language, ' + @into + ')
SELECT MR.Id, MR.Language, ' + @vals + '
FROM #missingRows MR
JOIN ' + @translationTableName + ' T ON T.Id = MR.Id AND T.Language = ''' + @sourceLanguage + ''''
--PRINT @sql
EXEC sp_executesql @statement = @sql
-- ---
SET @rowsInserted = @@ROWCOUNT
PRINT 'inserted [' + CAST(@rowsInserted AS VARCHAR) + '] rows'
-- ---

SET @sql = N'UPDATE ' + @translationTableName + ' SET
[Language] = [Language]
FROM ' + @translationTableName + ' X JOIN #existingRows ER ON X.Id = ER.Id
WHERE [Language] = ''xx-XX'''
--PRINT @sql
EXEC sp_executesql @statement = @sql

DROP TABLE #existingRows
END

-- ---
DROP TABLE #missingRows

END

使用sp_executesql,执行动态sql语句

USE [iForeningen]
GO
/****** Object: StoredProcedure [dbo].[usp_PrintInvoice] Script Date: 05/13/2013 11:28:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
--usp_PrintInvoice 52,NULL,NULL,NULL,NULL,1
ALTER PROCEDURE [dbo].[usp_PrintInvoice]
(
@SiteID int,
@InvoiceStartDate Datetime,
@InvoiceEndDate Datetime,
@InvoiceNoStart int,
@InvoiceNoEnd int,
@NewInvoice bit
)
AS
BEGIN

SET NOCOUNT ON;
DECLARE @WhereClause nvarchar(max)
Declare @SqlQuery nvarchar(max)
If (@NewInvoice = 1 and @InvoiceStartDate is null and @InvoiceEndDate is null and @InvoiceNoStart is null and @InvoiceNoEnd is null)
BEGIN
SET @WhereClause=' and i.PRINTEDDATE is null'
END
Else if(@NewInvoice = 1 and @InvoiceStartDate is not null and @InvoiceEndDate is null and @InvoiceNoStart is null and @InvoiceNoEnd is null)
BEGIN
SET @WhereClause= ' and i.PRINTEDDATE is null and INVOICEDATE >=@InvoiceStartDate'
END
Else if(@NewInvoice = 1 and @InvoiceStartDate is not null and @InvoiceEndDate is not null and @InvoiceNoStart is null and @InvoiceNoEnd is null)
BEGIN
SET @WhereClause=' and i.PRINTEDDATE is null and (INVOICEDATE >=@InvoiceStartDate and INVOICEDATE<=@InvoiceEndDate)'
END
Else if(@NewInvoice = 1 and @InvoiceStartDate is not null and @InvoiceEndDate is not null and @InvoiceNoStart is not null and @InvoiceNoEnd is null)
BEGIN
SET @WhereClause=' and i.PRINTEDDATE is null and (INVOICEDATE >=@InvoiceStartDate and INVOICEDATE<=@InvoiceEndDate) and i.INVOICENO >='+CAST(@InvoiceNoStart AS VARCHAR)+''
END
Else if(@NewInvoice = 1 and @InvoiceStartDate is not null and @InvoiceEndDate is not null and @InvoiceNoStart is not null and @InvoiceNoEnd is not null)
BEGIN
SET @WhereClause=' and i.PRINTEDDATE is null and (INVOICEDATE >=@InvoiceStartDate and INVOICEDATE<=@InvoiceEndDate) and (i.INVOICENO >='+CAST(@InvoiceNoStart AS VARCHAR)+' and i.INVOICENO <='+CAST(@InvoiceNoEnd AS VARCHAR)+')'
END
Else if (@NewInvoice = 0 and @InvoiceStartDate is not null and @InvoiceEndDate is not null and @InvoiceNoStart is null and @InvoiceNoEnd is null)
BEGIN
SET @WhereClause=' and (INVOICEDATE >=@InvoiceStartDate and INVOICEDATE<=@InvoiceEndDate)'
END
ELse if(@NewInvoice = 0 and @InvoiceStartDate is null and @InvoiceEndDate is not null and @InvoiceNoStart is null and @InvoiceNoEnd is null)
BEGIn
SET @WhereClause=' and (INVOICEDATE<=@InvoiceEndDate)'
END
ELse if(@NewInvoice = 0 and @InvoiceStartDate is null and @InvoiceEndDate is null and @InvoiceNoStart is not null and @InvoiceNoEnd is null)
BEGIN
SET @WhereClause=' and (i.INVOICENO >='+CAST(@InvoiceNoStart AS VARCHAR)+')'
END
ELse if(@NewInvoice = 0 and @InvoiceStartDate is null and @InvoiceEndDate is null and @InvoiceNoStart is null and @InvoiceNoEnd is not null)
BEgin
SET @WhereClause= ' and (i.INVOICENO <='+CAST(@InvoiceNoEnd AS VARCHAR)+')'
END
ELse if(@NewInvoice = 0 and @InvoiceStartDate is null and @InvoiceEndDate is null and @InvoiceNoStart is not null and @InvoiceNoEnd is not null)
BEGIN
SET @WhereClause=' and (i.INVOICENO >='+CAST(@InvoiceNoStart AS VARCHAR)+' and i.INVOICENO <='+CAST(@InvoiceNoEnd AS VARCHAR)+')'
END
ELse if(@NewInvoice = 0 and @InvoiceStartDate is not null and @InvoiceEndDate is null and @InvoiceNoStart is not null and @InvoiceNoEnd is not null)
BEGIN
SET @WhereClause= ' and (i.INVOICENO >='+CAST(@InvoiceNoStart AS VARCHAR) +' and i.INVOICENO <='+CAST(@InvoiceNoEnd AS VARCHAR)+')
and INVOICEDATE >=@InvoiceStartDate'
END
ELse if(@NewInvoice = 0 and @InvoiceStartDate is null and @InvoiceEndDate is not null and @InvoiceNoStart is not null and @InvoiceNoEnd is not null)
BEGIN
SET @WhereClause= 'and (i.INVOICENO >='+CAST(@InvoiceNoStart AS VARCHAR)+' and i.INVOICENO <='+CAST(@InvoiceNoEnd AS VARCHAR)+')
and INVOICEDATE <=@InvoiceEndDate'
END
ELse if(@NewInvoice = 0 and @InvoiceStartDate is not null and @InvoiceEndDate is not null and @InvoiceNoStart is not null and @InvoiceNoEnd is not null)
BEGIN
SET @WhereClause=
' and (i.INVOICENO >='+CAST(@InvoiceNoStart AS VARCHAR)+' and i.INVOICENO <='+CAST(@InvoiceNoEnd AS VARCHAR)+')
and (INVOICEDATE >=@InvoiceStartDate and INVOICEDATE<=@InvoiceEndDate)'
END

SET @SqlQuery='SELECT i.SITEID,i.INVOICENO,APRICE,il.DESCRIPTION,QUANTITY,DUEDATE,INVOICETOTAL,AMOUNTPAID,CUSTOMERNAME,ADDRESSLINE1,ADDRESSLINE2,ADDRESSLINE3,ZIPCODE,CITY,COUNTRY,MEMBERNO
FROM INVOICES i
inner join INVOICELINES il on i.INVOICENO = il.INVOICENO
inner join PERSONS p on i.PERSONID = p.PERSONID where i.SITEID='+CAST(@SiteID AS VARCHAR)+' and il.SITEID='+CAST(@SiteID AS VARCHAR)+' and p.SITEID='+CAST( @SiteID AS VARCHAR)+' ' + @WhereClause
print @WhereClause
print @SqlQuery
--Exec (@SqlQuery);
EXEC sp_executesql @SqlQuery,
N'@InvoiceStartDate datetime, @InvoiceEndDate datetime',
@InvoiceStartDate, @InvoiceEndDate


END

原文地址:https://www.cnblogs.com/cw_volcano/p/1947521.html