SQL动态查询返回varchar变量的日期

时间:2015-01-06 14:41:31

标签: sql date stored-procedures sql-server-2014-express

此程序应根据@refdate返回前一天。

如果我只在DB上执行此选择,它可以正常工作,但我的程序代码中出现了问题。

alter procedure [dbo].[SavePosition]
(@Refdate as varchar(15) =null)
as
begin try
set nocount on

declare @YdDate as varchar(15)

SELECT top 1 @YdDate = TradeDate from Trades where TradeDate < @Refdate ORDER BY TradeDate DESC;


declare @SQL AS VARCHAR(4000)

set @SQL='


Select  ('''+ @Refdate +''') AS Refdate, Prodname.name as Product, Inst.Name as Instrument,prodname.Id as prodId, Strat.Name as Strategy,Strat.Id as StratId, Pos.Tag, AssetGroup.name as AssetGroup, AssetClass.Name as AssetClass,

......[200 lines of code]..........

order by Strat.name,Prodname.Name
;'
EXEC(@SQL)
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber
     ,ERROR_SEVERITY() AS ErrorSeverity
     ,ERROR_STATE() AS ErrorState
     ,ERROR_PROCEDURE() AS ErrorProcedure
     ,ERROR_LINE() AS ErrorLine
     ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH
return

1 个答案:

答案 0 :(得分:2)

您不需要动态SQL ...在您进一步评论后转换为函数而不是存储过程。

CREATE FUNCTION [dbo].[teste1]
(@Refdate as varchar(15) =null)
RETURNS VARCHAR(15) AS
BEGIN
  declare @YdDate as varchar(15)

  SELECT TOP 1 @YdDate = TradeDate FROM Trades WHERE TradeDate < @Refdate 
  ORDER BY TradDate DESC;

  RETURN @YdDate
END

然后作为示例用法SELECT dbo.teste('2014-12-10')

显然,如果您的日期字符串以可以按字母顺序排序的格式存储(例如YYYYMMDD'20150106'

,那么这只会是可靠的