如何为select / update / delete语句创建存储过程

时间:2012-09-27 19:59:17

标签: sql database stored-procedures

我有这个sql语句,我想转换为存储过程。我怎样才能做到这一点?

select a.name, a.lastname, from myTable where b.name= a.lastname

由于

UPDATE 这会是对的吗

CREATE PROCEDURE myProcedure
AS
BEGIN
SELECT [a.name],
       [a.lastname]
FROM [myTable]
WHERE [b.name] = a.lastname
END

这是我正在努力的代码之一

sql语句

SELECT RTRIM(l.Lab1) + '/' + RTRIM(l.LabR) AS Lab, meta.Title,ls.[ID],ls.[surveyID], ls.[specialistID],ls.[isCompleted] FROM [MyDIM].[dbo].[lsLabSurvey] ls JOIN [MYDIM].[dbo].[dimDocMetaInfo] meta ON meta.id = ls.[surveyID] and specialistID = @PID and isCompleted=1 JOIN MyDatabase.DBO.PID_Table l ON ls.ID = l.ID

我的尝试存储过程

CREATE PROCEDURE PROCD1
AS
BEGIN
SELECT RTRIM(l.Lab1) + '/' + RTRIM(l.LabR) 
AS Lab, 
   meta.Title,
   la.[ID],
   ls.[surveyID],
   ls.[specialistID],
   ls.[isCompleted]
FROM [MyDIM].[dbo].[lsLabSurvey] ls 
JOIN [MyDIM].[dbo].[dimDocMetaInfo] meta 
ON meta.id = ls.[surveyID] 
and specialistID = @PID 
and isCompleted=1 
JOIN MyDatabase.DBO.PID_Table l 
ON ls.ID = l.ID 

END

2 个答案:

答案 0 :(得分:0)

真的不是那么难。你有95%的路在那里。以下内容适用于SQL Server:

CREATE PROCEDURE SomeProcedureName  
AS  
select a.name, a.lastname, from myTable where b.name= a.lastname

我强烈推荐这本书:http://www.barnesandnoble.com/w/sams-teach-yourself-sql-in-10-minutes-ben-forta/1100070678

它涵盖了基本的SQL语法,并提供了SQL的不同“方言”的示例。每个RDBMS执行类似功能的语法略有不同,您需要知道您正在使用的DB的方言。

答案 1 :(得分:0)

正如大卫所说,你几乎在那里但只是需要做些小改动。

  1. 我认为@Pid是一个参数,如果是,则存储过程定义中缺少它。
  2. (和specialistId = @ Pid和iscompleted = 1)形成Where子句(Filter表达式)。所以程序就像这样
  3. `

    CREATE PROCEDURE PROCD1 (@PID INT )
    AS 
        BEGIN
            SELECT  CONVERT(VARCHAR,RTRIM(l.Lab1)) + '/' + CONVERT(VARCHAR,RTRIM(l.LabR)) AS Lab ,
                    meta.Title ,
                    la.[ID] ,
                    ls.[surveyID] ,
                    ls.[specialistID] ,
                    ls.[isCompleted]
            FROM    [MyDIM].[dbo].[lsLabSurvey] ls
                    INNER JOIN [MyDIM].[dbo].[dimDocMetaInfo] meta ON meta.id = ls.[surveyID]
                    INNER JOIN MyDatabase.DBO.PID_Table l ON ls.ID = l.ID
            WHERE   ls.specialistID = @PID
                    AND ls.isCompleted = 1
        END 
    `
    

    希望这有帮助。