SQL函数错误:1064

时间:2012-04-19 00:22:22

标签: sql

我在SQL中创建自己的函数时遇到问题。我收到错误#1064 - 第10行的错误语法(带有'创建函数'的行),我无法弄清楚我做错了什么?

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'等。

4 个答案:

答案 0 :(得分:0)

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

拼写错误并使用保留字。

declare @ret varchar(10)

答案 1 :(得分: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

答案 2 :(得分: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')

答案 3 :(得分: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