Error "Conversion failed when converting date and/or time from character string" to execute one query in sql 2008 r2, run ok in 2005.

I have  a table-valued function that run in sql 2005 and when try to execute in sql 2008 r2, return the next "Conversion failed when converting date and/or time from character string".
USE [Runtime]
GO
/****** Object:  UserDefinedFunction [dbo].[f_Pinto_Graf_P_Opt]    Script Date: 06/11/2013 08:47:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   FUNCTION [dbo].[f_Pinto_Graf_P_Opt] (@fechaInicio datetime, @fechaFin datetime)  
-- Declaramos la tabla "@Produc_Opt" que será devuelta por la funcion
RETURNS @Produc_Opt table ( Hora datetime,NSACOS int, NSACOS_opt int)
AS  
BEGIN 
-- Crea el Cursor
DECLARE cursorHora CURSOR
READ_ONLY
FOR SELECT DateTime, Value FROM f_PP_Graficas ('Pinto_CON_SACOS',@fechaInicio, @fechaFin,'Pinto_PRODUCTO')
-- Declaracion de variables locales
DECLARE @produc_opt_hora int
DECLARE @produc_opt_parc int
DECLARE @nsacos int
DECLARE @time_parc datetime
-- Inicializamos VARIABLES
SET @produc_opt_hora = (SELECT * FROM f_Valor (@fechaFin,'Pinto_PRODUC_OPT'))
-- Abre y se crea el conjunto del cursor
OPEN cursorHora
-- Comenzamos los calculos 
FETCH NEXT FROM cursorHora INTO @time_parc,@nsacos
/************  BUCLE WHILE QUE SE VA A MOVER A TRAVES DEL CURSOR  ************/
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status = -2)
BEGIN
-- Terminamos la ejecucion 
BREAK
END
-- REALIZAMOS CÁLCULOS
SET @produc_opt_parc = (SELECT dbo.f_P_Opt_Parc (@fechaInicio,@time_parc,@produc_opt_hora))
-- INSERTAMOS VALORES EN LA TABLA
INSERT @Produc_Opt VALUES (@time_parc,@nsacos, @produc_opt_parc)
-- Avanzamos el cursor
FETCH NEXT FROM cursorHora INTO @time_parc,@nsacos
END
/************  FIN DEL BUCLE QUE SE MUEVE A TRAVES DEL CURSOR  ***************/
-- Cerramos el cursor
CLOSE cursorHora
-- Liberamos  los cursores
DEALLOCATE cursorHora
RETURN 
END

You can search the forums for that error message and find previous discussions - they all boil down to the same problem.  Somewhere in your query that calls this function, the code invoked implicitly converts from string to date/datetime.  In general,
this works in any version of sql server if the runtime settings are correct for the format of the string data.  The fact that it works in one server and not in another server suggests that the query executes with different settings - and I'll assume for
the moment that the format of the data involved in this conversion is consistent within the database/resultset and consistent between the 2 servers. 
I suggest you read Tibor's guide to the datetime datatype (via the link to his site below) first - then go find the actual code that performs this conversion.  It may not be in the function you posted, since that function also executes other functions. 
You also did not post the query that calls this function, so this function may not, in fact, be the source of the problem at all. 
Tibor's site

Similar Messages

  • Getting error " Conversion failed when converting date and/or time from character string."

    Hello Experts,
    I am getting the above error, when i try to execute the query. 
    DECLARE @START AS DATETIME
    DECLARE @END AS DATETIME
    SET @START = CONVERT(VARCHAR(10), GETDATE()-1,101) + '00:00:00'
    SET @END = CONVERT(VARCHAR(10), GETDATE()-1,101) + '23:59:59'
    Any suggestions as to how to get out of this error.
    Appreciate any help/suggestions.
    Thanks!
    Rahman

    Thanks Latheesh,
    I am able to execute the above query, but when i implement the same in my query, i am getting another error.
    Invalid column name 'DATETIME'.
    Invalid column name 'DATETIME'.
    Invalid column name 'DATETIME'.
    Invalid column name 'DATETIME'.
    DECLARE @START AS DATETIME
    DECLARE @END AS DATETIME
    SET @START = CONVERT(VARCHAR(10), GETDATE()-1,101) + ' 00:00:00'
    SET @END = CONVERT(VARCHAR(10), GETDATE()-1,101) + ' 23:59:59'
    SELECT
    SUBSTRING(A1.TGT,2,4) SATC,
    SUBSTRING(DGT,2,4) COFS,
    (CASE WHEN SG.S_G_E_NM LIKE '%S%' THEN 'SALES' WHEN SG.S_G_E_NM LIKE '%U%' THEN 'SUPPORT' WHEN SG.S_G_E_NM LIKE '%S%' THEN 'CUSTSERV' ELSE 'UNKNOWN' END) SKILL,
    COUNT(*) TOTAL,
    AVG(T1.NET) AS A,
    AVG(T1.TALK + T1.HOLD + T1.WORK) AVGHTIME
    FROM
    SELECT * FROM TABLE WHERE (1=1)
    AND DATETIME >= @START
    AND DATETIME <=@END
    AND PERIPH_ID IN (1111,2222,3333)
    AND TGT_ID NOT IN (12457)
    ANDSEQ_NBR IN (2)
    AND DGT LIKE '8%2400'
    AND TALK > 0
    ) AS T1
    Any guesses as to what could be going wrong here?
    Rahman

  • SAP query error - 1). [Microsoft][SQL Server Native Client 10.0][SQL Server]Conversion failed when converting date and/or time from character string.  'Received Alerts' (OAIB)

    SAP query error - 1). [Microsoft][SQL Server Native Client 10.0][SQL Server]Conversion failed when converting date and/or time from character string.  'Received Alerts' (OAIB)
    SELECT    
    CASE WHEN T0.DocStatus = 'O' THEN 'OPEN'
    WHEN T0.DocStatus = 'C' THEN 'CLOSED'  END  AS 'Document Status',
    T0.DocDate AS 'Posting Date',
    T0.DocNum AS 'Doc.No',
    T0.NumAtCard,
    T0.TransId AS 'Trans. No.',
    T0.Comments AS 'Remarks',
    T0.CardCode AS 'Offset Acct',
    T0.CardName AS 'Offset Acct Name',
    sum(T0.DocTotal) + (T0.WTSum) as 'DocTotal',
    T3.DueDate AS 'Cheque Date',
    T3.CheckSum AS 'Amount'
    FROM         ODPO AS T0 LEFT OUTER JOIN
                          VPM2 AS T1 ON T0.ObjType = T1.InvType AND T0.DocEntry = T1.DocEntry LEFT OUTER JOIN
         OVPM AS T2 ON T2.DocEntry = T1.DocNum LEFT OUTER JOIN
                          VPM1 AS T3 ON T2.DocEntry = T3.DocNum
    where T0.DocDate>='[%0]' and T0.DocDate<='[%1]'

    Hi,
    Try this:
    SELECT   
    CASE WHEN T0.DocStatus = 'O' THEN 'OPEN'
    WHEN T0.DocStatus = 'C' THEN 'CLOSED'  END  AS 'Document Status',
    T0.DocDate AS 'Posting Date',
    T0.DocNum AS 'Doc.No',
    T0.NumAtCard,
    T0.TransId AS 'Trans. No.',
    T0.Comments AS 'Remarks',
    T0.CardCode AS 'Offset Acct',
    T0.CardName AS 'Offset Acct Name',
    sum(T0.DocTotal) + (T0.WTSum) as 'DocTotal',
    T3.DueDate AS 'Cheque Date',
    T3.CheckSum AS 'Amount'
    FROM         ODPO  T0 LEFT OUTER JOIN
                          VPM2  T1 ON T0.ObjType = T1.InvType AND T0.DocEntry = T1.DocEntry
    LEFT OUTER JOIN
         OVPM  T2 ON T2.DocEntry = T1.DocNum LEFT OUTER JOIN
                          VPM1  T3 ON T2.DocEntry = T3.DocNum
    where T0.DocDate >= '[%0]' and T0.DocDate <='[%1]'
    group by T0.DocStatus,T0.DocDate ,
    T0.DocNum ,
    T0.NumAtCard,
    T0.TransId ,
    T0.Comments ,
    T0.CardCode,
    T0.CardName ,
    T0.WTSum ,
    T3.DueDate ,
    T3.CheckSum
    Thanks & Regards,
    Nagarajan

  • Conversion failed when converting date and/or time from character string

    Hi experts,
    I'm trying running a query in Microsoft Query but it gives the following error message:
    "conversion failed when converting date and/or time from character string"
    when asks me the data I'm inserting 31-01-2014
    i've copy the query form the forum:
    SELECT T1.CardCode, T1.CardName, T1.CreditLine, T0.RefDate, T0.Ref1 'Document Number',
         CASE  WHEN T0.TransType=13 THEN 'Invoice'
              WHEN T0.TransType=14 THEN 'Credit Note'
              WHEN T0.TransType=30 THEN 'Journal'
              WHEN T0.TransType=24 THEN 'Receipt'
              END AS 'Document Type',
         T0.DueDate, (T0.Debit- T0.Credit) 'Balance'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')<=-1),0) 'Future'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=0 and DateDiff(day, T0.DueDate,'[%1]')<=30),0) 'Current'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>30 and DateDiff(day, T0.DueDate,'[%1]')<=60),0) '31-60 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>60 and DateDiff(day, T0.DueDate,'[%1]')<=90),0) '61-90 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>90 and DateDiff(day, T0.DueDate,'[%1]')<=120),0) '91-120 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=121),0) '121+ Days'
    FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    WHERE (T0.MthDate IS NULL OR T0.MthDate > ?) AND T0.RefDate <= ? AND T1.CardType = 'C'
    ORDER BY T1.CardCode, T0.DueDate, T0.Ref1

    Hi,
    The above error appears due to date format is differnt from SAP query generator and SQL server.
    So you need convert all date in above query to SQL server required format.
    Try to convert..let me know if not possible.
    Thanks & Regards,
    Nagarajan

  • SSIS Lookup Conversion failed when converting date and/or time from character string

    Hi all,
    I'm trying to do a lookup by passing a date, however (i'm guessing) one of the dates is in a bad format and is failing the component.  How do I find the suspect row?  I set both lookup outputs to flat file but it is just erroring and not outputting
    anything.  The date being passed in is in datetime format and destination is the same data type.

    Thanks for your suggestions.  I have used ISDATE and MIN, MAX to find the maximum ranges.  ISDATE is not returning 0 in both Source and Destination (so it looks like they're all valid).  it looks like there are some null dates in from date
    column.  Would these throw a conversion error?  I'm still a bit stumped as to why i'm getting a conversion error, 1900-01-01 00:00:00.000 is still a valid date even if it's basically null.
    -- SOURCE MIN DATE = 2009-12-21 00:00:00.000
    -- SOURCE MAX DATE = 2015-06-08 00:00:00.000
    -- DESTINATION MIN FROM DATE = 1900-01-01 00:00:00.000
    -- DESTINATION MIN TO DATE = 2005-01-15 00:00:00.000
    -- DESTINATION MAX FROM DATE = 2015-10-18 00:00:00.000
    -- DESTINATION MAX TO DATE = 2145-12-31 00:00:00.000
    I will also try JAKUB's suggestion to see if the package completes with a few rows.

  • How to solve : Conversion failed when converting date and/or time from character string

    hi there
    my query :
    cmd = new SqlCommand("SELECT RTRIM(invoiceNo) as [Order No.],RTRIM(InvoiceDate) as [Order Date],RTRIM(SubTotal) as [SubTotal],RTRIM(VATPer) as [Vat+ST %],RTRIM(VATAmount) as [VAT+ST Amount],RTRIM(DiscountPer) as [Discount %],RTRIM(DiscountAmount) as [Discount Amount],RTRIM(GrandTotal) as [Grand Total],RTRIM(TotalPayment) as [Total Payment],RTRIM(PaymentDue) as [Payment Due] from Invoice_Info where InvoiceDate between @d1 and @d2 order by InvoiceDate desc", con);
    cmd.Parameters.Add("@d1", SqlDbType.DateTime, 30, "InvoiceDate").Value = dtpInvoiceDateFrom.Value.Date;
    cmd.Parameters.Add("@d2", SqlDbType.DateTime, 30, "InvoiceDate").Value = dtpInvoiceDateTo.Value.Date;
    i use date timepicker / vs2010 / sql server 2008 r2 
    tnx

    i change the type of my column(InvoiceDate column) to isDate but it doesnt work and error again ....
    What exactly does this mean? What was the data type before the change? What is it now? Can you show us the CREATE TABLE statement for the table?
    i want send my source code /database for you and you chek it plz
    Generally, you should not expect people to solve problem over mail. You can upload code and database to Dropbox, Skydrive or similar service if you people to look at it.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • SSRS error "Conversion failed when converting the nvarchar value"

    Hi folks!
    After SCCM 2012 R2 upgrade, we have errors with self made reports:
    An error has occurred during report processing. (rsProcessingAborted)
    Cannot read the next data row for the dataset DataSet2. (rsErrorReadingNextDataRow)
    Conversion failed when converting the nvarchar value '*****' to data type int.
    I found several articles to see reporting services log file for possible WMI related errors, but none exists. SQL server is 2008R2, Runned mofcomp, and re-installed reporting services role, but problem remains.
    I traced the dataset2 query:
    SELECT
      v_Collection_Alias.CollectionID ,v_Collection_Alias.Name
    FROM fn_rbac_Collection(@UserSIDs) v_Collection_Alias
    WHERE
     v_Collection_Alias.CollectionType = 2
    Any adwice is appreciated.
    ~Tuomas.

    Hi Tuomas,
    What's the SQL Server version? To verify the the SQL Server version, please see
    http://support.microsoft.com/kb/321185
    SCCM 2012 R2 need SQL Server 2008 R2 SP1 with CU 6 or SQL Server 2008 R2 with SP2 (http://technet.microsoft.com/en-us/library/gg682077.aspx#BKMK_SupConfigSQLSrvReq).
    If the SQL meets requirement, I would suggest you submit a thread to SQL forum to deal with the sql issue.
    Thanks.
    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

  • Conversion failed when converting the varchar value to data type int error

    Hi, I am working on a report which is off of survey information and I am using dynamic pivot on multiple columns.
    I have questions like Did you use this parking tag for more than 250 hours? If yes specify number of hours.
    and the answers could be No, 302, 279, No and so on....
    All these answers are of varchar datatype and all this data comes from a partner application where we consume this data for internal reporting.
    When I am doing dynamic pivot I get the below error.
    Error: Conversion failed when converting the varchar value 'No' to data type int.
    Query
    DECLARE @Cols1 VARCHAR(MAX), @Cols0 VARCHAR(MAX), @Total VARCHAR(MAX), @SQL VARCHAR(MAX)
    SELECT @Cols1 = STUFF((SELECT ', ' + QUOTENAME(Question) FROM Question GROUP BY Question FOR XML PATH('')),1,2,'')
    SELECT @Cols0 = (SELECT ', COALESCE(' + QUOTENAME(Question) + ',0) as ' + QUOTENAME(Question) FROM Question GROUP BY Question FOR XML PATH(''))
    SET @SQL = 'SELECT QID, QNAME' + @Cols0 + '
    FROM (SELECT QID, QNAME, ANSWERS, Question
    FROM Question) T
    PIVOT (MAX(ANSWERS) FOR Question IN ('+@Cols1+')) AS P'
    EXECUTE (@SQL)
    I am using SQL Server 2008 R2.
    Please guide me to resolve this.
    Thanks in advance..........
    Ione

    create table questions (QID int, QNAME varchar(50), ANSWERS varchar(500), Question varchar(50))
    Insert into questions values(1,'a','b','c'), (2,'a2','b2','c2')
    DECLARE @Cols1 VARCHAR(MAX), @Cols0 VARCHAR(MAX), @Total VARCHAR(MAX), @SQL VARCHAR(MAX)
    SELECT @Cols1 = STUFF((SELECT ', ' + QUOTENAME(Question) FROM Questions GROUP BY Question FOR XML PATH('')),1,2,'')
    SELECT @Cols0 = (SELECT ', COALESCE(' + QUOTENAME(Question) + ',''0'') as ' + QUOTENAME(Question) FROM Questions GROUP BY Question FOR XML PATH(''))
    SET @SQL = 'SELECT QID, QNAME' + @Cols0 + '
    FROM (SELECT QID, QNAME, ANSWERS, Question
    FROM Questions) T
    PIVOT (MAX(ANSWERS) FOR Question IN ('+@Cols1+')) AS P'
    EXECUTE (@SQL)
    drop table questions

  • Conversion failed when converting the varchar value 'undefined' to data typ

    Conversion failed when converting the varchar value 'undefined' to data type int.
    hi, i installed oracle insbridge following the instruction in the manual. in rate manager, when i tried to create a new "Normal rating" or "Underwriting", im getting the following exception
    Server Error in '/RM' Application.
    Conversion failed when converting the varchar value 'undefined' to data type int.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    Exception Details: System.Data.SqlClient.SqlException: Conversion failed when converting the varchar value 'undefined' to data type int.
    Source Error:
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
    Stack Trace:
    [SqlException (0x80131904): Conversion failed when converting the varchar value 'undefined' to data type int.]
    System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1948826
    System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4844747
    System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
    System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
    System.Data.SqlClient.SqlDataReader.HasMoreRows() +157
    System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout) +197
    System.Data.SqlClient.SqlDataReader.Read() +9
    System.Data.SqlClient.SqlCommand.CompleteExecuteScalar(SqlDataReader ds, Boolean returnSqlValue) +50
    System.Data.SqlClient.SqlCommand.ExecuteScalar() +150
    Insbridge.Net.Fwk.DAO.DataAccess.ScalarQuery(String connectionString, String command, Transaction transType, Object[] procParams) +110
    [Exception: Cannot Execute SQL Command: Conversion failed when converting the varchar value 'undefined' to data type int.]
    Insbridge.Net.Fwk.DAO.DataAccess.ScalarQuery(String connectionString, String command, Transaction transType, Object[] procParams) +265
    Insbridge.Net.Fwk.DAO.SqlProcessor.ExecuteScalarQueryProc(String subscriber, String datastore, String identifier, String command, Transaction transType, Object[] procParams) +101
    Insbridge.Net.Fwk.DAO.SqlProcessor.ExecuteScalarQuery(String subscriber, String identifier, String command) +22
    Insbridge.Net.RM.IBRM.ExeScalar(String cmd, Object[] paramsList) +99
    Insbridge.Net.RM.Components.Algorithms.AlgEdit.Page_Load(Object sender, EventArgs e) +663
    System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
    System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
    System.Web.UI.Control.OnLoad(EventArgs e) +99
    System.Web.UI.Control.LoadRecursive() +50
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
    my insbridge versions are as follows
    IBRU 4.0.0 Copyright ©2010, Oracle. All rights reserved. - Version Listing
    RMBUILD.DLL 4.0.0.0 (x86)
    SRLOAD.DLL 3.13.0 (x86)
    IBRM v04.00.0.17
    IB_CLIENT v04.00.0.00
    RM.DLL 4.00.0 (x86)
    IBFA 3.0.2
    OS: Windows Server 2003
    DB: Sql Server 2008
    Browser: IE8
    how do i solve this, please help

    This is an error due to conversion failed from character string to int datatype. Infact, the table column contains "NO" value which you are trying to convert to Int/SUM which is illegal. Without your code and table structure, its difficult to pinpoint your
    actual issue. But check, all columns for value "NO". 

  • Conversion failed when converting the varchar value to data type int

    Hi, I am unable to resolve this error and would like some assistance please.
    The below query produces the following error message -
    Msg 245, Level 16, State 1, Line 1
    Conversion failed when converting the varchar value 'NCPR' to data type int.
    Select Pc2.Assess,
                    Select Pc1.Title
                    From Pc1
                    Where Pc1.Assess = Pc2.Assess
                ) [Title]
            From Pc2
    However, when I run the query below I get the results shown in the image . Ie. nothing. Pc1 & Pc2 are aliases and are the same table and the assess field is an int. I found NCPR in one cell but that column (prop) is not used in the query. The table
    is nearly 25k rows.
    SELECT * FROM Pc1 WHERE Pc1.Assess LIKE '%NCPR%' OR ISNUMERIC(Pc1.Assess) = 0
    Thank you

    WHERE ISNUMERIC(id) = 1 and there are obviously no 'NCPR' records in the view as per my previous post.
    That is a bad assumption - SQL Server does not have to evaluate the query in the order you are expecting it to.
    Take this simple example
    CREATE TABLE #example
    col1 VARCHAR(50) NOT NULL
    INSERT INTO #example VALUES ('1'), ('2'), ('NaN')
    SELECT * FROM
    SELECT * FROM #example
    WHERE ISNUMERIC(col1) = 1
    ) X
    (3 row(s) affected)
    col1
    1
    2
    (2 row(s) affected)
    compare to
    CREATE TABLE #example
    col1 VARCHAR(50) NOT NULL
    INSERT INTO #example VALUES ('1'), ('2'), ('NaN')
    SELECT * FROM
    SELECT * FROM #example
    WHERE ISNUMERIC(col1) = 1
    ) X
    WHERE col1 = 1
    (3 row(s) affected)
    col1
    1
    Msg 245, Level 16, State 1, Line 8
    Conversion failed when converting the varchar value 'NaN' to data type int.

  • Conversion failed when converting the nvarchar value to data type int when returning nvarchar(max) from stored procedure

    Thank you for your help!!! 
    I've created a stored procedure to return results as xml.  I'm having trouble figuring out why I'm getting the error message "Conversion failed when converting the nvarchar value '<tr>.....'
    to data type int.    It seems like the system doesn't know that I'm returning a string... Or, I'm doing something that I just don't see.
    ALTER PROCEDURE [dbo].[p_getTestResults]
    @xml NVARCHAR(MAX) OUTPUT
    AS
    BEGIN
    CREATE TABLE #Temp
    [TestNameId] int,
    [MaxTestDate] [DateTime],
    [Name] [nvarchar](50),
    [Duration] [varchar](10)
    DECLARE @body NVARCHAR(MAX)
    ;WITH T1 AS
    SELECT DISTINCT
    Test.TestNameId
    , replace(str(Test.TotalTime/3600,len(ltrim(Test.TotalTime/3600))+abs(sign(Test.TotalTime/359999)-1)) + ':' + str((Test.TotalTime/60)%60,2)+':' + str(Test.TotalTime%60,2),' ','0') as Duration
    ,MaxTestDate = MAX(TestDate) OVER (PARTITION BY TM.TestNameId)
    ,TestDate
    ,TM.Name
    ,Test.TotalTime
    ,RowId = ROW_NUMBER() OVER
    PARTITION BY
    TM.TestNameId
    ORDER BY
    TestDate DESC
    FROM
    Test
    inner join TestName TM on Test.TestNameID = TM.TestNameID
    where not Test.TestNameID in (24,25,26,27)
    INSERT INTO #Temp
    SELECT
    T1.TestNameId
    ,T1.MaxTestDate
    ,T1.[Name]
    ,T1.Duration
    FROM
    T1
    WHERE
    T1.RowId = 1
    ORDER BY
    T1.TestNameId
    SET @body ='<html><body><H3>TEST RESULTS INFO</H3>
    <table border = 1>
    <tr>
    <th> TestNameId </th> <th> MaxTestDate </th> <th> Name </th> <th> Duration </th></tr>'
    SET @xml = CAST((
    SELECT CAST(TestNameId AS NVARCHAR(4)) as 'td'
    , CAST([MaxTestDate] AS NVARCHAR(11)) AS 'td'
    , [Name] AS 'td'
    , CAST([Duration] AS NVARCHAR(10)) AS 'td'
    FROM #Temp
    ORDER BY TestNameId
    FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
    SET @body = @body + @xml +'</table></body></html>'
    DROP TABLE #Temp
    RETURN @xml
    END
    closl

    Your dont need RETURN inside SP as you've declared @xml already as an OUTPUT parameter. Also you can RETURN only integer values using RETURN statement inside stored procedure as that's default return type of SP.
    so just remove RETURN statement and it would work fine
    To retrieve value outside you need to invoke it as below
    DECLARE @ret nvarchar(max)
    EXEC dbo.[P_gettestresults] @ret OUT
    SELECT @ret
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Conversion failed when converting nvarchar

    Forum,
    I have a set of data when when you try and make any amendments to the Business Partner Master screen and stock master data, the following error message appears:
    [Microsoft][SQL Native Client][SQL Server] Conversion failed when converting the nvarchar value '1553452 01' to data type int. (CINF)
    Again, it doesn't matter what's altered i.e. remarks, descriptions. The same error occurs.
    The system i am testing on is 8.81 PL06
    Has anyone come across this before?
    Regards,
    Juan

    1.Try to stop add-on if you have.
    2.If you have any UDF in master then check  that data type.
    3.If you have any FMS then also check there.
    Because  you have been tring to fill Nvarchar value in integer field.
    Thanks
    Manvendra Singh Niranjan

  • Error Message while adding Item in Item Master Data- [Microsoft][SQL Server Native Client 10.0][SQL Server]Conversion failed when converting the nvarchar value 's008 01' to data type int. (CINF)

    Dear Experts
    I am getting the following error message while adding item in Item Master data. I have modified the following SBO_SP_transactionNotification in SQL server after that could not able to add the item
    ALTER proc [dbo].[SBO_SP_TransactionNotification]
    @object_type nvarchar(20),                      -- SBO Object Type
    @transaction_type nchar(1),               -- [A]dd, [U]pdate, [D]elete, [C]ancel, C[L]ose
    @num_of_cols_in_key int,
    @list_of_key_cols_tab_del nvarchar(255),
    @list_of_cols_val_tab_del nvarchar(255)
    AS
    begin
    -- Return values
    declare @error  int                       -- Result (0 for no error)
    declare @error_message nvarchar (200)           -- Error string to be displayed
    select @error = 0
    select @error_message = N'Ok'
    --    IF @OBJECT_TYPE = '59' AND (@TRANSACTION_TYPE = 'A' or @TRANSACTION_TYPE = 'U')
      BEGIN
       IF EXISTS(
        SELECT T0.Price FROM IGN1 T0
        where  IsNull(T0.Price, '0') = '0' and T0.DocEntry = @list_of_cols_val_tab_del)
       BEGIN
        SELECT @ERROR=1,@ERROR_MESSAGE='Please insert the price !'
      END
    end
    -- Select the return values
    select @error, @error_message
    end

    Hi Rathna,
    Just put the SP like this, without the -- before the IF. A -- marks the line as a command therefore you need to uncomment and it will work.
    IF @OBJECT_TYPE = '59' AND (@TRANSACTION_TYPE = 'A' or @TRANSACTION_TYPE = 'U')
      BEGIN
       IF EXISTS(
        SELECT T0.Price FROM IGN1 T0
        where  IsNull(T0.Price, '0') = '0' and T0.DocEntry = @list_of_cols_val_tab_del)
       BEGIN
        SELECT @ERROR=1,@ERROR_MESSAGE='Please insert the price !'
      END
    end
    Hope it helps

  • Error in MS Visual Studio 2010 : Conversion failed when converting the nvarchar value '@VATSchemeType' to data type int.

    This worked well in Visual studio 2005, but in the 2010 version it gives the above error
    SELECT VT_ClientCore.ClientCode
     ,VT_VATScheme.SchemeName
          ,CI_Entity.Name as 'Client Name'
          ,SY_Address.Address1
     ,SY_Address.Address2
    ,SY_Address.Address3
     ,SY_Address.Address1
     +(CASE WHEN (Address2 is Null OR Address2 = '') THEN '' ELSE ', ' + Address2 END)
                      + (CASE WHEN (Address3 is Null OR Address3 = '') THEN '' ELSE ', ' + Address3 END)
                      as 'Address123'
    ,SY_Address.City
    ,VT_ClientCore.VATOffice
    ,VT_ClientCore.NatureOfBusiness
    ,SY_Address.PostalCode
    ,SY_Country.Description as 'Country'
    --CASE WHEN (PostalCode IS NULL THEN)
    FROM VT_ClientCore
    LEFT JOIN VT_ClientPack ON VT_ClientCore.EntityCode#ClientCore = VT_ClientPack.EntityCode#ClientCore
    LEFT JOIN VT_VATScheme ON VT_ClientPack.VATSchemeID = VT_VATScheme.VATSchemeID
    LEFT JOIN CI_Entity ON VT_ClientCore.EntityCode#ClientCore = CI_Entity.EntityCode
    LEFT JOIN CI_ENTITYDETAIL ON VT_ClientCore.Entitycode#ClientCore = CI_EntityDetail.EntityCode
    LEFT JOIN SY_Address ON CI_ENTITYDETAIL.AddressID = SY_Address.AddressID
    LEFT JOIN SY_Country ON VT_ClientCore.CountryCode = SY_Country.CountryCode
    --WHERE VT_ClientCore.ClientCode = '23002'
    --AND SY_Address.PostalCode IS NOT NULL
    WHERE CI_ENTITYDETAIL.DETAILTYPE = 'AT'
    AND VT_VATScheme.VATSchemeTypeID IN (@VATSchemeType)
    AND VT_VATScheme.VATSchemeID IN (@VATSchemeID)
    GROUP BY VT_ClientCore.ClientCode,CI_Entity.Name,SY_Address.City,VT_ClientCore.VATOffice,VT_ClientCore.NatureOfBusiness,SY_Address.PostalCode,SY_Address.Address1,SY_Address.Address2,SY_Address.Address3,VT_VATScheme.SchemeName
    ,SY_Country.Description
    --VAT Scheme
    SELECT VATSchemeID,SchemeName
    FROM VT_VATScheme
    WHERE VATSchemeTypeID IN (@VATSchemeType)
    ORDER BY SchemeName

    How are you assigning the value to variable @VATSchemaType? Are you assigning multiple values? if yes, then you need to better join with the values by splitting the values. 
    The below would give an error (just for your reference)
    create table test_one(col1 int)
    Insert into test_one Values(1),(2)
    Declare @inta varchar(10) = '1,2'
    Select * From test_one where col1 in(@inta)
    Select * From test_one where col1 in(Select items From dbo.Split_BigInt(@inta,','))
    Drop table test_one
    function definition:
    create FUNCTION Split_BigInt
    @string VARCHAR(MAX),
    @delimiter CHAR(1)
    RETURNS @results TABLE
    items BigInt
    AS
    BEGIN
    DECLARE @index INT
    DECLARE @temp TABLE (
    items BigInt)
    IF @string = ''
    RETURN
    SET @string = LTRIM(RTRIM(@string))
    SELECT @index = Charindex(@delimiter, @string)
    WHILE @index <> 0
    BEGIN
    INSERT INTO @temp (items)
    VALUES (LTRIM(RTRIM(LEFT(@string, @index - 1))))
    SELECT @string = LTRIM(RTRIM(RIGHT(@string, Len(@string) - @index)))
    SELECT @index = Charindex(@delimiter, @string)
    END
    INSERT INTO @temp (items)
    VALUES (@string)
    INSERT INTO @results (items)
    SELECT items
    FROM @temp
    where
    items <> ''
    RETURN
    END

  • Conversion failed when converting the nvarchar value 'MX_PERSON' to data type int

    Hi,
    I am trying to check user status by running this query: my query take as input the userid= 'USER1234' as parameter
    select count (distinct mskey) from idmv_vallink_basic_active where mcAttrName='MSKEYVALUE' and mcSearchValue='USER1234'
      and mskey in (select mskey from idmv_vallink_basic_active where mcattrname='MX_DEPARTEMENT' and mcsearchvalue between 20 and 50)
      and mskey in (select mskey from idmv_vallink_basic_active where mcattrname='Z_TYPE' and mcsearchvalue = 'LOCAL')
      and mskey not in (select mskey from idmv_vallink_basic_active where mcattrname='ZPOSITION1' and mcsearchvalue = '12345') 
      and mskey not in (select mskey from idmv_vallink_basic_active where mcattrname='ZPOSITION2' and mcsearchvalue = '12345')
    I am using IDM 7.2 Sp7.
    Can you help me to correct this query? Should I use idmv_entry_simple as start?
    Michaela

    Hi Michaela,
    I would recommend you to use idmv_value_* for non reference attributes and idmv_link_* for reference attributes for performance reasons. Try this:
    count (distinct mskeyvalue.mskey) from idmv_value_basic_active mskeyvalue, idmv_value_basic_active department,
    idmv_value_basic_active type_, idmv_value_basic_active position1, idmv_value_basic_active position2
    where mskeyvalue.SearchValue = 'MSKEYVALUE' and mskeyvalue.SearchValue = 'USER1234'
    and department.SearchValue = 'MX_DEPARTEMENT' and department.SearchValue between 20 and 50
    and type_.SearchValue = 'Z_TYPE' and type_.SearchValue = 'LOCAL'
    and position1.SearchValue = 'ZPOSITION1' and position1.SearchValue = '12345'
    and position2.SearchValue = 'ZPOSITION2' and position2.SearchValue = '12345'
    and mskeyvalue.mskey = department.mskey and mskeyvalue.mskey = type_.mskey and mskeyvalue.mskey = position1.mskey
    and mskeyvalue.mskey = position2.mskey
    Regards
    Norman

Maybe you are looking for