SQL这个语法有什么问题? BEGIN ... IF ... RETURN

时间:2017-05-16 16:34:43

标签: sql tsql sql-server-2014

以下是一个功能的摘录。我一直收到语法错误

  

关键字'RETURN'

附近的语法不正确

我的代码:

dom.forms.datetype

2 个答案:

答案 0 :(得分:1)

但仍然缺少替换逻辑; - )

CREATE FUNCTION dbo.convttxt (@mhtztxt VARCHAR(MAX))
RETURNS FLOAT
AS
BEGIN
    DECLARE @mhtz FLOAT 

    IF ISNUMERIC(LTRIM(RTRIM(@mhtztxt))) = 1 
       SET @mhtz = CONVERT(FLOAT, LTRIM(RTRIM(@mhtztxt))) 
    ELSE
    SELECT @mhtz = 
                     REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(name, 'xyz', 0)              
              ,'<Enter Text Here>', 0)
              ,'<Enter Text Here>', 0)
              ,'<Enter Text Here>', 0)
              ,'<Enter Text Here>', 0)
              ,'<Enter Text Here>', 0)
              ,'<Enter Text Here>', 0)
              ,'<Enter Text Here>', 0) 

                 FROM sys.all_objects
    ;

    RETURN @mhtz
END

答案 1 :(得分:0)

这是固定的(但@tgr打败了我)。

ALTER FUNCTION dbo.convttxt (@mhtztxt VARCHAR(MAX))
RETURNS FLOAT AS
BEGIN
  DECLARE @mhtz FLOAT;
  --below: extra parenthesis removed, variable spelled wrong, ISNUMERIC statement was not complete

  IF ISNUMERIC(ltrim(rtrim(@mhtztxt)))=1 
  --RETURN convert(FLOAT, ltrim(rtrim(@mhtztxt))) 
    SET @mhtz = convert(FLOAT, ltrim(rtrim(@mhtztxt)));
  ELSE
  SET @mhtz= 
    (SELECT TOP(1)
        REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([COL1] 
                ,'xyz', 0)              
                ,'<Enter Text Here>', 0)
                ,'<Enter Text Here>', 0)
                ,'<Enter Text Here>', 0)
                ,'<Enter Text Here>', 0)
                ,'<Enter Text Here>', 0)
                ,'<Enter Text Here>', 0)
                ,'<Enter Text Here>', 0) 
                from (SELECT 1.00 UNION ALL SELECT 2.00) table1(col1)); -- emulating your table

   RETURN @mhtz;
END -- needed an End

你可以这样进一步简化:

ALTER FUNCTION dbo.convttxt (@mhtztxt VARCHAR(MAX))
RETURNS FLOAT AS
BEGIN
  RETURN
    CASE 
      WHEN ISNUMERIC(ltrim(rtrim(@mhtztxt)))=1 
      THEN convert(FLOAT, ltrim(rtrim(@mhtztxt)))
      ELSE
      (SELECT TOP(1)
          REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([COL1] 
                  ,'xyz', 0),'<Enter Text Here>', 0),'<Enter Text Here>', 0)
                  ,'<Enter Text Here>', 0),'<Enter Text Here>', 0),'<Enter Text Here>', 0)
                  ,'<Enter Text Here>', 0),'<Enter Text Here>', 0) 
                  from (SELECT 1.00 UNION ALL SELECT 2.00) table1(col1)) -- emulating your table
    END
END