问题创建存储过程

时间:2018-01-11 03:19:37

标签: sql-server stored-procedures

我在SQL Server中创建存储过程时遇到问题;有什么我错过/做错了吗?

我添加了查询来创建数据库并创建程序,非常感谢您的帮助和指导。

如果您需要更多详细信息,请告诉我们!

存储过程(麻烦)

USE [ChartSample]  
GO  

SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  

ALTER PROCEDURE [dbo].[SC_GetPlayers]  
AS  
BEGIN  
    SELECT  *  
    FROM CS_Player   
END  

USE [ChartSample]  
GO  

SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  

ALTER PROCEDURE [dbo].[SC_GetPlayerRecordsBtPlayerId] 
    @PlayerId INT  
AS  
BEGIN  
    SELECT  
        PlayerId, 
        Year,  
        TotalRun, TotalWickets,  
        ODIMatches, TestMatches  
    FROM    
        CS_PlayerRecord  
    WHERE   
        PlayerId = @PlayerId  
END 

错误讯息:

  

Msg 154,Level 15,State 1,Procedure SC_GetPlayers,Line 8 [Batch Start Line 7]
  过程,函数或触发器中不允许使用USE数据库语句。

     

Msg 208,Level 16,State 6,Procedure SC_GetPlayerRecordsBtPlayerId,Line 1 [Batch Start line 21]
  无效的对象名称'dbo.SC_GetPlayerRecordsBtPlayerId'。

查询创建小型数据库:

CREATE DATABASE ChartSample  

USE [ChartSample]  
GO  

SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  
SET ANSI_PADDING ON  
GO  

CREATE TABLE [dbo].[CS_Player]
(  
    [PlayerId] [int] IDENTITY(1,1) NOT NULL,  
    [PlayerName] [varchar](50) NULL,  

    CONSTRAINT [PK_CS_Player] 
        PRIMARY KEY CLUSTERED ([PlayerId] ASC)
) ON [PRIMARY]  
GO  

SET ANSI_PADDING OFF  
GO  

SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  

CREATE TABLE [dbo].[CS_PlayerRecord]
(  
    [ID] [int] IDENTITY(1,1) NOT NULL,  
    [PlayerId] [int] NULL,  
    [Year] [int] NULL,  
    [TotalRun] [int] NULL,  
    [TotalWickets] [int] NULL,  
    [ODIMatches] [int] NULL,  
    [TestMatches] [int] NULL,  

    CONSTRAINT [PK_CS_PlayerRecord] 
        PRIMARY KEY CLUSTERED ([ID] ASC)
) ON [PRIMARY]  
GO  

ALTER TABLE [dbo].[CS_layerRecord]  WITH CHECK 
    ADD CONSTRAINT [FK_CS_PlayerRecord_CS_Player] 
        FOREIGN KEY([PlayerId]) REFERENCES [dbo].[CS_Player]([PlayerId])  
GO  

ALTER TABLE [dbo].[CS_PlayerRecord] CHECK CONSTRAINT [FK_CS_PlayerRecord_CS_Player]  
GO 

2 个答案:

答案 0 :(得分:0)

在第二个GO声明之前添加USE

同样正如旁注所示,您可能想要拼写第二个存储过程: GetPlayerRecordsByPlayerID

答案 1 :(得分:0)

尝试在两个proc之间使用GO,否则它将被视为SC_GetPlayers proc代码的一部分。使用GO将有助于编译器理解它是批处理的结束

编辑:似乎您正在尝试创建过滤器,因此请使用Create代替Alter

Create PROC [dbo].[SC_GetPlayers]  
AS  
    BEGIN  
        SELECT  *  
        FROM    CS_Player   
    END  

GO--here

USE [ChartSample]  
GO  
SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  
Create PROC [dbo].[SC_GetPlayerRecordsBtPlayerId] @PlayerId INT  
..