Question : syntax error converting char string to smalldatetime

this is my error:  
Server: Msg 295, Level 16, State 3, Procedure, procedurename, Line 28
Syntax error converting character string to smalldatetime data type.

this is my proc:


IF OBJECT_ID('procedurename','p') IS NOT NULL
DROP PROC procedurename
GO
CREATE PROCEDURE procedurename (
 @topcount int,
 @tsdate smalldatetime=NULL,
 @latencytype char(2)=NULL,
 @msgsource char(1)=NULL
)
AS
SET NOCOUNT ON


IF(@tsdate IS NULL)
BEGIN
  --if the parm is passed null, just get the max value (should use idx effectively)
  SELECT @tsdate = MAX(tsdate)FROM database.dbo.maintable
END
  --remove the time portion
--  SET @tsdate = CONVERT(SMALLDATETIME,CONVERT(VARCHAR(20),@tsdate,120),120)
  SELECT @tsdate = CONVERT(VARCHAR(10),@tsdate,120)


 DECLARE @SQL VARCHAR(5)
  SET @SQL = 'SELECT TOP '+ CAST(@topcount AS VARCHAR)  
 ' OrderNo,MsgSource,Latency,LatencyType,tsdate
FROM database.dbo.maintable WITH (NOLOCK)
WHERE ('+@tsdate+' IS NULL OR tsdate = '+@tsdate+')
AND ('+@latencytype+' IS NULL OR LatencyType = '+@latencytype+')
AND ('+@msgsource+' IS NULL OR MsgSource='+@MsgSource+')
ORDER BY LatencyType,Latency DESC '

PRINT(@SQL)
--EXEC(@SQL)
GO

I am embarrassed that I haven't found it yet.  Does anybody see it?

Answer : syntax error converting char string to smalldatetime

this should do:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
IF OBJECT_ID('procedurename','p') IS NOT NULL
DROP PROC procedurename
GO
CREATE PROCEDURE procedurename (
 @topcount int,
 @tsdate smalldatetime=NULL,
 @latencytype char(2)=NULL,
 @msgsource char(1)=NULL
)
AS
SET NOCOUNT ON 

IF(@tsdate IS NULL)
BEGIN
  --if the parm is passed null, just get the max value (should use idx effectively)
  SELECT @tsdate = MAX(tsdate)FROM database.dbo.maintable
END 
 DECLARE @SQL VARCHAR(5000)
  SET @SQL = 'SELECT TOP '+ CAST(@topcount AS VARCHAR)  
 ' OrderNo,MsgSource,Latency,LatencyType,tsdate 
  FROM database.dbo.maintable WITH (NOLOCK)
  WHERE tsdate >= CONVERT(datetime, '''+ CONVERT(varchar(10), @tsdate, 120) +''', 120 )
  AND  tsdate < DATEADD(day, 1, CONVERT(datetime, '''+ CONVERT(varchar(10), @tsdate, 120) +''', 120 ))
  ' + CASE WHEN @latencytype IS NULL THEN '' ELSE ' AND LatencyType = '''+@latencytype+''' ' END 
    + CASE WHEN @msgsource IS NULL THEN '' ELSE ' AND MsgSource='''+@MsgSource+''' ' END 
   + ' ORDER BY LatencyType,Latency DESC ' 
PRINT(@SQL)
--EXEC(@SQL)
GO
Open in New Window Select All
Random Solutions  
 
programming4us programming4us