Ошибка conversion failed when converting from a character string to uniqueidentifier

Created a stored procedure in SQL 9 (2005) and have since upgraded to SQL 10 (2008). Since then, the following stored procedure has stopped working and thrown up the above error:

ALTER PROCEDURE [dbo].[GetModifiedPages] 
    @vPortalUID         nvarchar(32) = ''
AS
BEGIN
    -- Convert GUID to UI
    DECLARE @nPortalUID AS uniqueidentifier
    SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)

The passed in param @vPortalUID contains: 2A66057D-F4E5-4E2B-B2F1-38C51A96D385. I execute the stored proc like this:

EXEC GetModifiedPages '2A66057D-F4E5-4E2B-B2F1-38C51A96D385'

It falls over. I have tried Convert aswell. Still no joy. Have also had the value going in with { } around it. I removed these programatically and manually as above.

If you are interested I am running the SP from an ASP Classic page, although that should not affect this as the above code was run using SSMS.

Thanks in advance for your help.
James

asked Sep 25, 2009 at 11:49

jamesmhaley's user avatar

jamesmhaleyjamesmhaley

44.4k11 gold badges35 silver badges49 bronze badges

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

Emma Thapa's user avatar

Emma Thapa

7471 gold badge7 silver badges14 bronze badges

answered Sep 25, 2009 at 12:03

KM.'s user avatar

2

I’ve been getting the error «Conversion failed when converting from a character string to uniqueidentifier» and am finally at the end of my rope. I’ve narrowed down my problem to as small as possible while keeping the error in tact. Install the CSV splitter from here first if you want to reproduce:

http://www.sqlservercentral.com/articles/Tally+Table/72993/

Here’s the test code. I’m on SQL 2008R2 but in a database that is SQL 2005 compatible:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ZZZTESTTABLE]') AND type in (N'U'))
DROP TABLE [dbo].[ZZZTESTTABLE]
GO

CREATE TABLE [dbo].[ZZZTESTTABLE](
    [Col1] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_ZZZTESTTABLE] PRIMARY KEY CLUSTERED 
(
    [Col1] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

-- Test table that I would like to check my values against
insert dbo.ZZZTESTTABLE(Col1) values('85B049B7-CDD0-4995-B582-5A74523039C0')

-- Test string that will be split into table in the DelimitedSplit8k function
declare @temp varchar(max) = '918E809E-EA7A-44B5-B230-776C42594D91,6F8DBB54-5159-4C22-9B0A-7842464360A5'

-- I'm trying to delete all data in the ZZZTESTTABLE that is not in my string but I get the error 
delete dbo.ZZZTESTTABLE
where Col1 not in 
(
-- ERROR OCCURS HERE
    select cast(Item as uniqueidentifier) from dbo.DelimitedSplit8K(@temp, ',')
)

HERE’s the source for the DelimitedSplit8K function so you don’t have to go and find it:

CREATE FUNCTION dbo.DelimitedSplit8K
--===== Define I/O parameters
        (@pString VARCHAR(8000), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
     -- enough to cover VARCHAR(8000)
  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "zero base" and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT 0 UNION ALL
                 SELECT TOP (DATALENGTH(ISNULL(@pString,1))) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT t.N+1
                   FROM cteTally t
                  WHERE (SUBSTRING(@pString,t.N,1) = @pDelimiter OR t.N = 0) 
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY s.N1),
        Item       = SUBSTRING(@pString,s.N1,ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000))
   FROM cteStart s
;

  • Remove From My Forums
  • Question

  • I have an issue where a UNIQUEIDENTIFIER field contains a NULL value.

    Essentially, I have a custom Scalar-Valued Function that accepts an NVARCHAR(50) parameter, and when attempting to use this function in a SELECT Statement I’m getting the error noted in the Title.

    Example:

    SELECT dbo.ListManual(CONVERT(NVARCHAR(50), ISNULL(LookupID, »))) AS Listing FROM EnrolleeExtensionBase

    If the LookupID field (UNIQUEIDENTIFIER) contains a valid GUID, this works fine — however if it is NULL it is unable to do a conversion to a blank string.

    I have tried to use COALESCE as follows:

    SELECT COALESCE(CONVERT(NVARCHAR(50), LookupID), ») FROM EnrolleeExtensionBase

    Which, returns a wonderful valid result set of GUIDs and blanks.

    However, if I try to put the same logic as a parameter to my Function it again gives problems with converting:

    SELECT dbo.ListManual(COALESCE(CONVERT(NVARCHAR(50), LookupID), »)) AS Listing FROM EnrolleeExtensionBase

    Attempting to CAST or CONVERT the COALESCE results to a string does not have any effect on the resulting data type and still throws the same error with conversion.

    Basically, this seems to be an issue with attempting to convert a GUID field with possible blank values to a string as an inline process.

    Any ideas?

Answers

  • How about another guess.  Is there somewhere in your function that you convert the uniqueidentifier (either explicitly or implicitly — for example if you compare the nvarchar(50) parameter to a uniqueidentifier variable or column, SQL will attempt to
    convert the nvarchar to a uniqueidentifier (because uniqueidentifier has a higher precedence).  If that is true, you are not getting the error in the function call, but somewhere in the function.  For example, if I run

    Create Table dbo.FooTable(FooGuid uniqueidentifier default NewID());
    Insert dbo.FooTable(FooGuid) Default Values;
    Insert dbo.FooTable(FooGuid) Values (Null);
    go
    
    Create Function dbo.FooFunction (@Input nvarchar(50)) Returns nvarchar(50) As
    Begin
     Return @Input;
    End
    go
    
    Select FooGuid, dbo.FooFunction(COALESCE(CONVERT(NVARCHAR(50), FooGuid), '')) AS Listing 
    From dbo.FooTable;
    
    Select FooGuid, dbo.FooFunction(COALESCE(CONVERT(NVARCHAR(50), FooGuid), '')) AS Listing 
    From dbo.FooTable
    Where FooGuid = dbo.FooFunction(COALESCE(CONVERT(NVARCHAR(50), FooGuid), ''));
    
    
    go
    Drop Function dbo.FooFunction;
    Drop Table dbo.FooTable;
    

    the first select runs fine, but the second select gets a conversion error because the nvarchar(50) result of an empty string is implicitly converted in the WHERE clause.

    Tom

    • Marked as answer by

      Thursday, March 3, 2011 7:17 AM

yafidik

0 / 0 / 0

Регистрация: 13.10.2014

Сообщений: 13

1

18.08.2016, 02:56. Показов 15790. Ответов 5

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Выдаёт данную ошибку для тех кто разбирается

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
System.Data.SqlClient.SqlException произошло
  HResult=-2146232060
  Message=Conversion failed when converting from a character string to uniqueidentifier.
  Source=.Net SqlClient Data Provider
  ErrorCode=-2146232060
  Class=16
  LineNumber=1
  Number=8169
  Procedure=""
  Server=(LocalDB)v11.0
  State=2
  StackTrace:
       в System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       в System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       в System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       в System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       в System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
       в System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       в System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       в WindowsFormsApplication1.reg.button1_Click(Object sender, EventArgs e) в d:Program Filestest c#1WindowsFormsApplication1WindowsFormsApplication1reg.cs:строка 26
  InnerException:

вот сам код

C#
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
namespace WindowsFormsApplication1
{
    public partial class reg : Form
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)v11.0;AttachDbFilename=D:Program Filestest c#1WindowsFormsApplication1WindowsFormsApplication1Data.mdf;Integrated Security=True;Connect Timeout=30;");
        public reg()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlDataAdapter sda = new SqlDataAdapter("insert into LOGIN (Id,login,pasword,status)values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"')",con);
            sda.SelectCommand.ExecuteNonQuery();// тут ошибку выдаёт
            con.Close();
 
            MessageBox.Show("Регестрация прошла успешно");
            con.Close();
            
        }
       public static void main(string[] args)
       {
           Application.Run(new reg());
       }
 
       private void reg_Load(object sender, EventArgs e)
       {
 
       }
    }
}

вопрос что может быть какая проблема и как решить.
P.S. ну я так понял что с бд ошибка но что именно я не понял … изучать с# только начал не будьте строги и если не составит труда объясните подробнее
P.S.S Адмны извените если не в ту темы написал ну я посчитал что эта самая подходящяя …



0



OwenGlendower

Администратор

Эксперт .NET

15668 / 12629 / 5003

Регистрация: 17.03.2014

Сообщений: 25,712

Записей в блоге: 1

18.08.2016, 10:38

2

Лучший ответ Сообщение было отмечено yafidik как решение

Решение

yafidik, текст ошибки «Conversion failed when converting from a character string to uniqueidentifier» говорит сам за себя. Какая-то из колонок имеет тип uniqueidentifier (по другому GUID), а значение которое ты передал в INSERT не получается преобразовать в него. Предполагаю что это колонка Id. У тебя в коде Id берется из textBox1 что врядли имеет сиысл т.к. ключи это внутренняя кухня БД и пользователи их не видят и не вводят. Вместо этого можно подставить функцию NEWID которая сгенерирует новый GUID. При желании можно сгенерировать Guid и на стороне C# через Guid.NewGuid.

Вместо SqlDataAdapter я бы использовал SqlCommand и что самое важное передавал бы значения колонок через SqlParameter т.к. это более безопасно и обеспечивает более высокую производительность SQL Server.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const string CONNECTION_STRING = @"Data Source=(LocalDB)v11.0;AttachDbFilename=D:Program Filestest c#1WindowsFormsApplication1WindowsFormsApplication1Data.mdf;Integrated Security=True;Connect Timeout=30;";
 
private void button1_Click(object sender, EventArgs e)
{
    using (var con = new SqlConnection(CONNECTION_STRING))
    {
        var cmd = new SqlCommand("insert into LOGIN (Id,login,pasword,status) values(NEWID(),@login,@password,@status)", con);
        cmd.Parameters.AddWithValue("@login", textBox2.Text);
        cmd.Parameters.AddWithValue("@password", textBox3.Text);
        cmd.Parameters.AddWithValue("@status", textBox4.Text);
        con.Open();
        cmd.ExecuteNonQuery();
    }
    MessageBox.Show("Регестрация прошла успешно");
}



1



1109 / 847 / 496

Регистрация: 09.04.2014

Сообщений: 2,002

18.08.2016, 10:39

3

Лучший ответ Сообщение было отмечено yafidik как решение

Решение

у вас в таблице LOGIN поле Id описано как uniqueidentifier, т.е. Guid, а в textBox1 вы вводите что-то, что текстовым представлением Guid не является



1



0 / 0 / 0

Регистрация: 13.10.2014

Сообщений: 13

18.08.2016, 11:08

 [ТС]

4

nedel, OwenGlendower, спасибо огромное … глупая ошибка …. а мучился второй день …. можно закрывать тему… вопрос решён
P.S. я на форумах редко сижу обычно после решения проблем пишут можно закрыть тему … вот и я также XD



0



OwenGlendower

18.08.2016, 11:13

Не по теме:

Цитата
Сообщение от yafidik
Посмотреть сообщение

обычно после решения проблем пишут можно закрыть тему … вот и я также

Обычно после этого тему не закрывают. Вот и сейчас так же :read:



0



0 / 0 / 0

Регистрация: 13.10.2014

Сообщений: 13

19.08.2016, 20:32

 [ТС]

6

OwenGlendower, я форумы как то не очень любил и изредка пользовался… так что извините…



0



  • Remove From My Forums
  • Question

  • Hello,

    I have to admit I am bad with SQL. I have a scenario where one of the TFS 2015 view stores the team project name as GUID which is of type nvarchar. Now I need to provide users name of the projects rather than ID in my report. I have another view in
    TFS 2015 which gives me the name of the projects. I thought of writing a join statement for this two views and get the project names. So I went with this below query and just to keep you on the same page, team project name in the first view has GUID and name
    as well. As the older projects are migrated from TFS 2012.

    System.TeamProject has team project name (older project name from TFS 2012) and id for new projects (TFS 2015). So in short it has names and Id’s stored in it. I want to get only names as an output in my report to get further report set up.

    SELECT * FROM [dbo].[vw_denorm_WorkItemCoreLatest] wi
    INNER JOIN [dbo].vw_projects p ON wi.[System.TeamProject] = p.project_id
    UNION ALL
    SELECT * FROM [dbo].[vw_denorm_WorkItemCoreLatest] wi
    INNER JOIN [dbo].vw_projects p ON wi.[System.TeamProject] = p.project_name

    For now I have * in my query. I know the second part of the query works fine and return data for projects which has name stored. However those with guid id return the error.

    Msg 8169, Level 16, State 2, Line 1 Conversion failed when converting from a character string to uniqueidentifier.

    I have checked this issue online and saw many suggestions. However I am still not able to solve it. I understood one is nvarchar and project_id is uniqueidentifier. However what modification should I make in SQL query ? 

    First view:

    Second view: 

    Thanks & Regards,

    Ahetejazahmad Khan.


    Ahetejazahmad Khan.

Answers

  • Ok, I have resolved this issue based on Vishe and  Hilary inputs. Below is the correct query and correct type casting.

    select distinct p.project_name, p.project_id from [dbo].[vw_projects] p
    INNER JOIN [dbo].[vw_denorm_WorkItemCoreLatest] wi
    on wi.[System.TeamProject] = convert(nvarchar(36), p.project_id)
    OR  wi.[System.TeamProject] = p.project_name

    Hopefully it will be useful for others.

    Thanks & Regards,

    Ahetejazahmad Khan.


    Ahetejazahmad Khan.

    • Marked as answer by

      Monday, November 7, 2016 7:06 AM

    • Unmarked as answer by
      Ahetejaz
      Monday, November 7, 2016 8:08 AM
    • Marked as answer by
      Ahetejaz
      Monday, November 7, 2016 8:08 AM

  • Ошибка control channel disconnect exception
  • Ошибка content not found
  • Ошибка content manager assetto corsa
  • Ошибка contactor inpl 115 steer
  • Ошибка contact your support personnel