Pergunta

Eu quero criar uma coluna Varchar no SQL que deve conter N'guid' enquanto guid é um GUID gerado por .NET (GUID.NewGuid) - Class System.guid.

Qual é o comprimento do varchar Eu deveria esperar de um GUID? É um comprimento estático?

Devo usar nvarchar (Guid jamais usará caracteres Unicode)?

varchar(Guid.Length)

Ps. Não quero usar um tipo de dados do SQL Row GUID. Estou apenas perguntando o que é Guid.MaxLength.

Foi útil?

Solução

Depende de como você formate o GUID:

  • Guid.NewGuid().ToString() => 36 caracteres (hifenizado)
    Saídas: 12345678-1234-1234-1234-123456789abc

  • Guid.NewGuid().ToString("D") => 36 caracteres (hifenizado, o mesmo que ToString())
    Saídas: 12345678-1234-1234-1234-123456789abc

  • Guid.NewGuid().ToString("N") => 32 caracteres (apenas dígitos)
    Saídas: 12345678123412341234123456789abc

  • Guid.NewGuid().ToString("B") => 38 caracteres (aparelho)
    Saídas: {12345678-1234-1234-1234-123456789abc}

  • Guid.NewGuid().ToString("P") => 38 Personagens (parênteses)
    Saídas: (12345678-1234-1234-1234-123456789abc)

  • Guid.NewGuid().ToString("X") => 68 caracteres (hexadecimal)
    Saídas: {0x12345678,0x1234,0x1234,{0x12,0x34,0x12,0x34,0x56,0x78,0x9a,0xbc}}

Outras dicas

36, e o GUID usará apenas 0-9a-f (hexidecimal!).

12345678-1234-1234-1234-123456789012

São 36 caracteres em qualquer guia-eles são de comprimento constante. Você pode ler um pouco mais sobre os meandros de GUIDS aqui.

Você precisará de mais dois comprimentos se quiser armazenar o aparelho.

Nota: 36 é o comprimento da string com os traços intermediários. Na verdade, são números de 16 bytes.

o correto coisa a fazer aqui é armazená -lo como uniqueidentifier - Isso é totalmente indexível, etc. no banco de dados. A próxima melhor opção seria uma binary(16) Coluna: os GUIDs padrão têm exatamente 16 bytes de comprimento.

Se você precisar armazená -lo como uma string, o comprimento realmente se resume a como você escolhe codificá -lo. Como hexadecimal (também conhecido como codificação base-16) sem hífens, seriam 32 caracteres (dois dígitos hexadecimais por byte), então char(32).

No entanto, você pode querer Para armazenar os hífens. Se você tem pouco espaço, mas seu banco de dados não suporta blobs / guids nativamente, você pode usar Base64 codificando e remova o == sufixo preenchido; Isso lhe dá 22 caracteres, então char(22). Não há necessidade de usar Unicode, e não há necessidade de comprimento variável - então nvarchar(max) Seria uma má escolha, por exemplo.

I believe GUIDs are constrained to 16-byte lengths (or 32 bytes for an ASCII hex equivalent).

GUIDs are 128bits, or

0 through ffffffffffffffffffffffffffffffff (hex) or 
0 through 340282366920938463463374607431768211455 (decimal) or 
0 through 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 (binary, base 2) or 
0 through 91"<b.PX48m!wVmVA?1y (base 95)

So yes, min 20 characters long, which is actually wasting more than 4.25 bits, so you can be just as efficient using smaller bases than 95 as well; base 85 being the smallest possible one that still fits into 20 chars:

0 through -r54lj%NUUO[Hi$c2ym0 (base 85, using 0-9A-Za-z!"#$%&'()*+,- chars)

:-)

22 bytes, if you do it like this:

System.Guid guid = System.Guid.NewGuid();
byte[] guidbytes = guid.ToByteArray();
string uuid = Convert.ToBase64String(guidbytes).Trim('=');

Binary strings store raw-byte data, whilst character strings store text. Use binary data when storing hexi-decimal values such as SID, GUID and so on. The uniqueidentifier data type contains a globally unique identifier, or GUID. This value is derived by using the NEWID() function to return a value that is unique to all objects. It's stored as a binary value but it is displayed as a character string.

Here is an example.

USE AdventureWorks2008R2;
GO
CREATE TABLE MyCcustomerTable
(
    user_login   varbinary(85) DEFAULT SUSER_SID()
    ,data_value   varbinary(1)
);
GO

INSERT MyCustomerTable (data_value)
    VALUES (0x4F);
GO

Applies to: SQL Server The following example creates the cust table with a uniqueidentifier data type, and uses NEWID to fill the table with a default value. In assigning the default value of NEWID(), each new and existing row has a unique value for the CustomerID column.

-- Creating a table using NEWID for uniqueidentifier data type.  
CREATE TABLE cust  
(  
 CustomerID uniqueidentifier NOT NULL  
   DEFAULT newid(),  
 Company varchar(30) NOT NULL,  
 ContactName varchar(60) NOT NULL,   
 Address varchar(30) NOT NULL,   
 City varchar(30) NOT NULL,  
 StateProvince varchar(10) NULL,  
 PostalCode varchar(10) NOT NULL,   
 CountryRegion varchar(20) NOT NULL,   
 Telephone varchar(15) NOT NULL,  
 Fax varchar(15) NULL  
);  
GO  
-- Inserting 5 rows into cust table.  
INSERT cust  
(CustomerID, Company, ContactName, Address, City, StateProvince,   
 PostalCode, CountryRegion, Telephone, Fax)  
VALUES  
 (NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,  
 '90110', 'Finland', '981-443655', '981-443655')  
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',  
 '08737-363', 'Brasil', '(14) 555-8122', '')  
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,   
 '1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')  
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,  
 '8010', 'Austria', '7675-3425', '7675-3426')  
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,  
 'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');  
GO
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top