簡體   English   中英

在SQL語句中聲明變量

[英]Declare variable in a SQL statement

我想知道是否可以在sql select查詢中創建變量。
以下示例中的解釋,我們從過去一個月(或更早)發布/更新的城市中選擇新聞:

set @monthBack = 1; -- one month back in time
set @cityName = "Berlin"; -- take a city name

select n.title, coalesce (n.releaseDate, n.updateDate) as news_date 
from news as n
inner join with cities as c on c.id = n.cityid
where 
    c.name = @cityName and
    year(coalesce (n.releaseDate, n.updateDate)) = 
                                 year(current_date - interval @monthBack month)
    month(coalesce (n.releaseDate, n.updateDate)) = 
                                 month(current_date - interval @monthBack month)
order by coalesce (n.releaseDate, n.updateDate)

如果未定義發布日期,則新聞日期為更新日期。

因此,我想用特定於具體select語句的特定變量替換coalesce (n.releaseDate, n.updateDate)的重復coalesce (n.releaseDate, n.updateDate) ...

mysql數據庫中有可能嗎?

PS。

由於“問題”更多地與sql語法和代碼的可讀性有關,我只想通過修改sql代碼來解決它,而不是將其應用於外部工具或創建其他對象(例如視圖或表)(對於某些語法而言,不值得如此復雜)優化)

我可以想到許多解決問題的方法,但我不確定哪一種是最好的。

您可以執行“; With”子查詢來確定“ coalesce(n.releaseDate,n.updateDate)”的值,然后在下面的查詢中使用它。

或使用存儲過程或函數獲取正確的參數

您可以在表格新聞上查看並添加一列,其值為“ coalesce(n.releaseDate,n.updateDate)”

或者,您也可以執行以下操作:

set @monthBack = 1; -- one month back in time
DECLARE @Query NVarchar(Max),
        @NewsDate NVARCHAR(MAX)

SET @NewsDate = coalesce (n.releaseDate, n.updateDate) -- Determine the value here

SET @Query = 
'select n.title, '+@NewsDate+' as news_date 
 from news as n
 inner join with cities as c on c.id = n.cityid
 where 
     c.name='Berlin' and
     year('+@NewsDate+') = 
                                  year(current_date - interval @monthBack month)
     month('+@NewsDate+')) = 
                                  month(current_date - interval @monthBack month)
 order by '+@NewsDate

execute sp_executesql @Query

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM