我正在使用SQL Server 2008 R2 我有这样的商店程序:
CREATE PROCEDURE Get_Code_Tourne_Matin
-- Add the parameters for the stored procedure here
@The_FA int,
@The_Jour int,
@The_Insee varchar(10)
AS
BEGIN
declare @TheCode varchar(250)
set @TheCode = case
when exists (SELECT T_TOURNE_LABEL.LIBELLE
FROM TOURNE
LEFT JOIN T_TOURNE_LABEL ON TOURNE.LIB_TOURNE = T_TOURNE_LABEL.NOID
WHERE THE_FA = @The_FA AND
NO_INSEE = @The_Insee AND
JOUR = @The_Jour AND
(datepart(hh, LE_HEURE) between 13 and 23 or datepart(hh, LE_HEURE) between 0 and 6)) then LIBELLE
when exists (SELECT LIBELLE
FROM TOURNE
LEFT JOIN T_TOURNE_LABEL ON TOURNE.LIB_TOURNE = T_TOURNE_LABEL.NOID
WHERE THE_FA = @The_FA AND
NO_INSEE = @The_Insee AND
JOUR = 0 AND
(datepart(hh, LE_HEURE) between 13 and 23 or datepart(hh, LE_HEURE) between 0 and 6)) then LIBELLE
else '00'
end
RETURN @TheCode
END
我只想归还libelle
当发现第一个选择3变量然后重新启动libelle
否则如果在找到时选择2变量,则返回libelle
否则后退'00'
似乎LIBELLE上的语法错误
任何想法?
答案 0 :(得分:3)
我认为:
set @TheCode = COALESCE(
(SELECT TOP 1 T_TOURNE_LABEL.LIBELLE
FROM TOURNE
LEFT JOIN T_TOURNE_LABEL ON TOURNE.LIB_TOURNE = T_TOURNE_LABEL.NOID
WHERE THE_FA = @The_FA AND
NO_INSEE = @The_Insee AND
(JOUR = @The_Jour OR JOUR = 0) AND
(datepart(hh, LE_HEURE) between 13 and 23 or datepart(hh, LE_HEURE) between 0 and 6)
ORDER BY JOUR DESC), '00')
应涵盖所有案件。 (如果您的查询中永远不会有两个匹配的行,其中一行有JOUR = @The_Jour
而另一行有JOUR = 0
,那么您可以删除TOP 1
和ORDER BY
子句(请注意我假设任何可能的@The_Jour
值都是> 0)
答案 1 :(得分:0)
set @TheCode =( SELECT ISNULL(( SELECT TOP 1 T_TOURNE_LABEL.LIBELLE
FROM TOURNE
LEFT JOIN T_TOURNE_LABEL ON TOURNE.LIB_TOURNE = T_TOURNE_LABEL.NOID
WHERE THE_FA = @The_FA AND NO_INSEE = @The_Insee AND JOUR = @The_Jour
AND ( DATEPART(hh, LE_HEURE) BETWEEN 13 AND 23
OR DATEPART(hh, LE_HEURE) BETWEEN 0 AND 6
)), '00') AS LIBELLE
答案 2 :(得分:0)
CREATE PROCEDURE Get_Code_Tourne_Matin
@The_FA int,
@The_Jour int,
@The_Insee varchar(10)
AS
BEGIN
declare @TheCode varchar(250)
Set @TheCode = '';
SELECT top 1 @TheCode = T_TOURNE_LABEL.LIBELLE
FROM TOURNE
LEFT JOIN T_TOURNE_LABEL ON TOURNE.LIB_TOURNE = T_TOURNE_LABEL.NOID
WHERE THE_FA = @The_FA AND
NO_INSEE = @The_Insee AND
(JOUR = @The_Jour or JOUR = 0 )AND
(datepart(hh, LE_HEURE) between 13 and 23 or datepart(hh, LE_HEURE) between 0 and 6)
set @TheCode = case
when len(@TheCode) > 0
when exists (SELECT @TheCode)
else '00'
end
RETURN @TheCode
END