November 13, 2014 at 7:36 pm
The below code is throwing error
Conversion failed when converting date and/or time from character string.
DECLARE @QUERY VARCHAR(MAX)
DECLARE @STARTTIME DATETIME
DECLARE @ProdDBName_testlog VARCHAR(30)
DECLARE @ProdTableName_testlog VARCHAR(30)
SET @ProdDBName_testlog = master
SET @ProdTableName_testlog = 'employee'
SET @QUERY = N'SELECT ' +@STARTTIME+'= STARTTIME FROM ' +@ProdDBName_testlog+'.dbo.'+@ProdTableName_testlog
EXEC (@QUERY)
DATETIME format:'2014-07-01 00:03:43.000'
Even I write Convert (varchar(30),startime) in the query it is throwing error.Plz help
November 13, 2014 at 7:56 pm
To me, it looks like you are trying to get a value from a log table and assign it to variable @STARTTIME. When you use the EXEC command, all of your variables are not visible to the command you are executing.
One way to work around this is to create a temporary table and insert you start time into that. Temporary tables are scoped so that they are visible to the EXEC command.
IF I am right, something like the following should work for you....
DECLARE @QUERY VARCHAR(MAX)
DECLARE @STARTTIME DATETIME
DECLARE @ProdDBName_testlog VARCHAR(30)
DECLARE @ProdTableName_testlog VARCHAR(30)
SET @ProdDBName_testlog = master
SET @ProdTableName_testlog = 'employee'
CREATE TABLE #DateTable (StartTime DATETIME)
SET @QUERY = N'INSERT INTO #DateTable SELECT STARTTIME FROM ' +@ProdDBName_testlog+'.dbo.'+@ProdTableName_testlog
EXEC (@QUERY)
SELECT @STARTTIME = StartTime FROM #DateTable
November 14, 2014 at 8:29 am
You don't need to use an additional table. You just need to use the dynamic sql correctly.
DECLARE @QUERY NVARCHAR(4000)
DECLARE @STARTTIME DATETIME
DECLARE @ProdDBName_testlog VARCHAR(30)
DECLARE @ProdTableName_testlog VARCHAR(30)
SET @ProdDBName_testlog = 'master'
SET @ProdTableName_testlog = 'employee'
SET @QUERY = N'SELECT @STARTTIME = STARTTIME FROM ' + QUOTENAME(@ProdDBName_testlog)+'.dbo.'+QUOTENAME(@ProdTableName_testlog)
EXEC sp_executesql @QUERY, N'@STARTTIME DATETIME OUTPUT', @STARTTIME OUTPUT
SELECT @STARTTIME
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply