需要将 GUID 更改为 varchar 或 char

Need to change GUID to varchar or char

我正在尝试使用参考 table 来更新代码,但出现错误:

Conversion failed when converting from a character string to uniqueidentifier

ID 是一个 guid:086B9FE7-3980-47D7-BB05-003708F1D564 我想使用的参考代码是 4 个字符,比如 H100

当我尝试更改 table 中的数据类型然后使用引用 table 中的值更新文件时收到初始错误。我试过根据其他文章进行转换和转换,但即使我转换或转换成功,我仍然得到相同的消息。

参考表:

Id                                   |  ReportCode
6340FCEA-161C-42F4-8D7F-46B4C2E6C4E2 |  H100

数据表:

CauseId
6340FCEA-161C-42F4-8D7F-46B4C2E6C4E2

我用来尝试更新的代码。第一个有效,第二个带来错误消息:

select cast(nvarchar(36), ID) as ID
from [dbo].[reftable]

UPDATE dbo.datatable
SET    causeid = L.reportcode
FROM   dbo.datatable S 
join dbo.reftable L on S.causeid = L.id

Uniqueidentifier 是一种特殊的列类型,它包含 36 个字节,中间有一些连字符。分配与其格式不匹配的字符串值在尝试转换时总是会失败。

-- Conversion failed when converting from a character string to uniqueidentifier.
SELECT CONVERT(UNIQUEIDENTIFIER, 'H100')

-- OK
SELECT CONVERT(UNIQUEIDENTIFIER, 'c029f8be-29dc-41c1-8b38-737b4cc5a4df')

如果您想使用一个普通的 VARCHAR 作为您的新 causeid 值,您需要先将列类型转换为 VARCHAR(或 NVARCHAR)。

ALTER TABLE dbo.datatable ALTER COLUMN causeid VARCHAR(200) -- NOT NULL if you need

如果您无法更改数据类型,可能是因为有一个 INDEXCONSTRAINT 链接到它。当您尝试更改时,SQL 引擎会告诉您哪个对象链接到它。您将不得不删除它们,更改列类型,然后重新创建它们。

我使用这些查询来检查索引和约束。我更新了 table.

的搜索值
DECLARE @table_name VARCHAR(200) = 'datatable'
DECLARE @column_name VARCHAR(200) = 'causeid'

 -- Indexes
SELECT
     SchemaName = SCHEMA_NAME(t.schema_id),
     TableName = t.name,
     IndexName = ind.name,
     IndexType = CASE ind.index_id WHEN 0 THEN 'Heap' WHEN 1 THEN 'Clustered' ELSE 'Nonclustered' END,
     Disabled = ind.is_disabled,
     ColumnOrder = ic.index_column_id,
     ColumnName = col.name,
     ColumnType = y.name,
     ColumnLength = y.max_length,
     ColumnIncluded = ic.is_included_column
FROM 
    sys.indexes ind 
    INNER JOIN sys.index_columns ic ON  ind.object_id = ic.object_id and ind.index_id = ic.index_id 
    INNER JOIN sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id 
    INNER JOIN sys.tables t ON ind.object_id = t.object_id 
    INNER JOIN sys.types y ON y.user_type_id = col.user_type_id
WHERE 
    t.is_ms_shipped = 0 AND
    t.name = @table_name AND
    col.name = @column_name
ORDER BY
    SchemaName,
    t.name, 
    ind.name, 
    ic.index_column_id

-- Constraints
SELECT 
    TableName = t.Name,
    ColumnName = c.Name,
    dc.Name,
    dc.definition
FROM 
    sys.tables t
    INNER JOIN sys.default_constraints dc ON t.object_id = dc.parent_object_id
    INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND c.column_id = dc.parent_column_id
WHERE
    t.name = @table_name AND
    c.name = @column_name
ORDER BY 
    t.Name