【问题标题】:Convert SQL procedure to function将 SQL 过程转换为函数
【发布时间】:2020-09-30 13:40:43
【问题描述】:
create function fiyathesapla(@StartDate datetime2(5),@EndDate datetime2(5),@kodu nvarchar(max))
returns table
as
return (

WITH theDates AS
     (SELECT @StartDate as theDate
      UNION ALL
      SELECT DATEADD(day, 1, theDate)
        FROM theDates
       WHERE DATEADD(day, 1, theDate) <= @EndDate
     )
SELECT SUM( v_period.fiyat-((v_period.fiyat/100)*v_period.indirim))  FROM theDates,v_period  WHERE tarih1<=theDates.theDate and tarih2>=theDates.theDate  and  vkodu=@kodu
)
go

---错误码---

消息 4514,第 16 级,状态 1,程序 fiyathesapla,第 6 行 [批处理开始第 0 行] CREATE FUNCTION 失败,因为没有为第 1 列指定列名。

我在尝试创建函数时收到此错误。 它有助于通过逐天计算两个输入的日期来计算价格。 但是当我创建存储过程时它可以工作。 我想创建一个函数,如何编辑它。

---正常运行的程序代码---

USE [villapaket1]
GO
/****** Object:  StoredProcedure [dbo].[FN_fiyat]    Script Date: 30.09.2020 16:18:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[FN_fiyat] @StartDate datetime2(5),@EndDate datetime2(5),@kodu nvarchar(max)
AS

WITH theDates AS
    (SELECT @StartDate as theDate
     UNION ALL
     SELECT DATEADD(day, 1, theDate)
       FROM theDates
      WHERE DATEADD(day, 1, theDate) <= @EndDate
    )
SELECT SUM( v_period.fiyat-((v_period.fiyat/100)*v_period.indirim))  FROM theDates,v_period  WHERE tarih1<=theDates.theDate and tarih2>=theDates.theDate  and  vkodu=@kodu

【问题讨论】:

  • 您的代码不是 MySQL。它看起来像 SQL Server,所以我添加了那个标签。
  • 看起来数据库引擎告诉你SUM( v_period.fiyat-((v_period.fiyat/100)*v_period.indirim))(=最终select的第一列)需要一个别名。这不是在函数外部显示结果所必需的,但它返回具有有效列名的表所必需的。
  • 问题出在“WITH theDates AS”

标签: sql-server tsql stored-functions


【解决方案1】:

看起来数据库引擎告诉您SUM( v_period.fiyat-((v_period.fiyat/100)*v_period.indirim))(= 最终选择的第一列)需要一个别名。这不是在函数外部显示结果所必需的,但它返回具有有效列名的表所必需的。

this fiddle 下方和this fiddle 中使用小数据集和简单(但类似)功能进行问题再现。

样本数据

create table MyTable
(
  id int
);

insert into MyTable (id) values
(100), (101), (102);

选择

with cte as
(
  select id-100 as NewId from MyTable
)
select sum(cte.NewId) --> no column alias, works fine (result table has unnamed column)
from cte;

功能

create function MyFunction()
returns table
as return
(
  with cte as
  (
    select id-100 as NewId from MyTable
  )
  select sum(cte.NewId) --> no column alias, does NOT work
  from cte
);

CREATE FUNCTION 失败,因为没有为第 1 列指定列名。

更新到工作功能:

create function MyFunction()
returns table
as return
(
  with cte as
  (
    select id-100 as NewId from MyTable
  )
  select sum(cte.NewId) as IdSum --> with column alias
  from cte
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 2011-08-08
    • 2016-04-21
    • 2012-08-10
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多