2012-04-19 90 views
0

我在創建自己的函數時遇到了問題。我得到一個錯誤#1064 - 錯誤的語法在第10行(與'創建函數'一行),我無法弄清楚我做錯了什麼?SQL函數錯誤:1064

create table students (
id int primary key, 
name varchar(30), 
surname varchar(30), 
class char(4), 
born datetime, 
grade varchar(10) 
) 

create function returnGrade 
(@class char(4)) 
return varchar(10) 
AS 
BEGIN 
declare @return varcahr(10) 
@class = SUBSTRING(@class, 2, 1) 
    SELECT @return = CASE @class 
    WHEN '1' then 'first' 
    WHEN '2' then 'second' 
    WHEN '3' then 'third' 
    WHEN '4' then 'fourth' 
    ELSE 'unknown' 
    END 
return @return 
END 

PS變量類看起來是這樣的: 'T3.A', 'T4.A', 'T4.B' 等

+0

嘗試在create table和create function之間添加一個'GO'。另外,'declare @return varcahr(10)'應該是'varchar(10)' – 2012-04-19 00:25:10

+0

以及..我添加了GO並且它寫道「你有一個1064 err在線#9附近'go create function returnGrade .. 。「 – SukiCZ 2012-04-19 00:29:24

回答

0

您的代碼: declare @return varcahr(10)

兩個錯字和使用保留字。

declare @ret varchar(10)

0

請嘗試如下,在你的語句返回(一個或多個)丟失。

create function returnGrade 
(
    @class char(4) 
) 
returns varchar(10) 
AS 
BEGIN 
    declare @return varchar(10) 
    set @class = SUBSTRING(@class, 2, 1) 
     SELECT @return = CASE @class 
     WHEN '1' then 'first' 
     WHEN '2' then 'second' 
     WHEN '3' then 'third' 
     WHEN '4' then 'fourth' 
     ELSE 'unknown' 
    END 

    return @return 
END 
+0

這是一樣的。 SQL不能通過'create function returnGrade'這一行: -/ – SukiCZ 2012-04-19 00:33:27

0

由於您沒有提到我將它視爲SQL Server的數據庫。

您的代碼中有幾個拼寫錯誤。

這裏是校正

create function returnGrade 
(@class char(4)) 
returns varchar(10) -- returns not return 
AS 
BEGIN 
declare @return varchar(10) -- varchar not varcahr 
set @class = SUBSTRING(@class, 2, 1) -- set was missing 
    SELECT @return = CASE @class 
    WHEN '1' then 'first' 
    WHEN '2' then 'second' 
    WHEN '3' then 'third' 
    WHEN '4' then 'fourth' 
    ELSE 'unknown' 
    END 
return @return 
END 

上面的代碼編譯罰款和太返回值。

select dbo.returngrade('A2') 
0

以下適用於我。

CREATE TABLE students 
    (
     id INT PRIMARY KEY , 
     name VARCHAR(30) , 
     surname VARCHAR(30) , 
     class CHAR(4) , 
     born DATETIME , 
     grade VARCHAR(10) 
    ) 

GO -- Added GO 


CREATE FUNCTION returnGrade (@class CHAR(4)) 
RETURNS VARCHAR(10) -- Changed to RETURNS from RETURN 
AS 
    BEGIN 
     DECLARE @return VARCHAR(10) -- Corrected the typo varcahr 
     SET @class = SUBSTRING(@class, 2, 1) -- Added SET 
     SELECT @return = CASE @class 
          WHEN '1' THEN 'first' 
          WHEN '2' THEN 'second' 
          WHEN '3' THEN 'third' 
          WHEN '4' THEN 'fourth' 
          ELSE 'unknown' 
          END 
     RETURN @return 
    END 

GO 
+0

這寫道:「在'GO ...'附近的第11行寫錯了: - / – SukiCZ 2012-04-19 07:48:43