FORMAT (Transact-SQL)FORMAT (Transact-SQL)
Aplica-se a:Applies to: SQL ServerSQL Server (todas as versões compatíveis)
SQL ServerSQL Server (all supported versions)
Banco de Dados SQL do AzureAzure SQL Database
Banco de Dados SQL do AzureAzure SQL Database
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Azure Synapse AnalyticsAzure Synapse Analytics
Azure Synapse AnalyticsAzure Synapse AnalyticsAplica-se a:Applies to:
SQL ServerSQL Server (todas as versões compatíveis)
SQL ServerSQL Server (all supported versions)
Banco de Dados SQL do AzureAzure SQL Database
Banco de Dados SQL do AzureAzure SQL Database
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Azure Synapse AnalyticsAzure Synapse Analytics
Azure Synapse AnalyticsAzure Synapse Analytics
Retorna um valor formatado com o formato e a cultura opcional especificados.Returns a value formatted with the specified format and optional culture. Use a função FORMAT para formatação com reconhecimento de localidade de valores de data/hora e número como cadeias de caracteres.Use the FORMAT function for locale-aware formatting of date/time and number values as strings. Para conversões de tipos de dados gerais, use CAST ou CONVERT.For general data type conversions, use CAST or CONVERT.
Convenções da sintaxe Transact-SQL
Transact-SQL Syntax Conventions
SintaxeSyntax
FORMAT( value, format [, culture ] )
注意
Para ver a sintaxe do Transact-SQL para o SQL Server 2014 e versões anteriores, confira a Documentação das versões anteriores.To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.
ArgumentosArguments
valuevalue
Expressão de um tipo de dados com suporte para formatação.Expression of a supported data type to format. Para obter uma lista de tipos válidos, consulte a tabela na seção Comentários.For a list of valid types, see the table in the following Remarks section.
formatformat
Padrão de formato nvarchar.nvarchar format pattern.
O argumento format deve conter uma cadeia de formato válido do .NET Framework, como uma cadeia de formato padrão (por exemplo, "C" ou "D") ou como um padrão de caracteres personalizados para obter datas e valores numéricos (por exemplo, "MMMM DD, aaaa (dddd)").The format argument must contain a valid .NET Framework format string, either as a standard format string (for example, "C" or "D"), or as a pattern of custom characters for dates and numeric values (for example, "MMMM DD, yyyy (dddd)"). A formatação composta não tem suporte.Composite formatting is not supported. Para obter uma explicação completa sobre esses padrões de formatação, veja a documentação do .NET Framework sobre formatação de cadeias de caracteres em geral, formatos personalizados de data e hora e formatos personalizados de número.For a full explanation of these formatting patterns, consult the .NET Framework documentation on string formatting in general, custom date and time formats, and custom number formats. Um bom ponto de partida é o tópico, "Formatando tipos".A good starting point is the topic, "Formatting Types."
culturaculture
Argumento nvarchar opcional especificando uma cultura.Optional nvarchar argument specifying a culture.
Se o argumento culture não for fornecido, o idioma da sessão atual será usado.If the culture argument is not provided, the language of the current session is used. Esse idioma é definido implícita ou explicitamente com o uso da instrução SET LANGUAGE.This language is set either implicitly, or explicitly by using the SET LANGUAGE statement. culture aceita qualquer cultura compatível com .NET Framework como um argumento. Ela não é limitada aos idiomas explicitamente compatíveis com SQL ServerSQL Server.culture accepts any culture supported by the .NET Framework as an argument; it is not limited to the languages explicitly supported by SQL ServerSQL Server. Se o argumento culture não for válido, FORMAT gerará um erro.If the culture argument is not valid, FORMAT raises an error.
Tipos de retornoReturn Types
nvarchar ou nulonvarchar or null
A extensão do valor retornado é determinada pelo format.The length of the return value is determined by the format.
ComentáriosRemarks
FORMAT retorna NULL para erros que não uma cultura que não é valid.FORMAT returns NULL for errors other than a culture that is not valid. Por exemplo, NULL será retornado se o valor especificado em format não for válido.For example, NULL is returned if the value specified in format is not valid.
A função FORMAT é não determinística.The FORMAT function is nondeterministic.
FORMAT conta com a presença do CLR (Common Language Runtime) do .NET Framework.FORMAT relies on the presence of the .NET Framework Common Language Runtime (CLR).
Essa função não pode ser remota, uma vez que ela depende da presença do CLR.This function cannot be remoted since it depends on the presence of the CLR. Tornar remota uma função que exige o CLR pode provocar um erro no servidor remoto.Remoting a function that requires the CLR, could cause an error on the remote server.
FORMAT depende de regras de formatação CLR, que determinam que pontos e vírgulas e pontos finais devem ser ignorados.FORMAT relies upon CLR formatting rules, which dictate that colons and periods must be escaped. Portanto, quando a cadeia de caracteres de formato (segundo parâmetro) contém uma vírgula ou ponto, a vírgula ou o ponto devem ser precedidos por uma barra invertida quando um valor de entrada (primeiro parâmetro) é do tipo de dados time.Therefore, when the format string (second parameter) contains a colon or period, the colon or period must be escaped with backslash when an input value (first parameter) is of the time data type. Veja D. FORMAT com tipos de dados de tempo.See D. FORMAT with time data types.
A tabela a seguir lista os tipos de dados aceitáveis para o argumento value, junto com os tipos equivalentes de mapeamento do .NET Framework.The following table lists the acceptable data types for the value argument together with their .NET Framework mapping equivalent types.
CategoriaCategory | TypeType | Tipo .NET.NET type |
---|---|---|
NuméricoNumeric | BIGINTbigint | Int64Int64 |
NuméricoNumeric | INTint | Int32Int32 |
NuméricoNumeric | SMALLINTsmallint | Int16Int16 |
NuméricoNumeric | TINYINTtinyint | ByteByte |
NuméricoNumeric | decimaldecimal | SqlDecimalSqlDecimal |
NuméricoNumeric | numericnumeric | SqlDecimalSqlDecimal |
NuméricoNumeric | FLOATfloat | DoubleDouble |
NuméricoNumeric | realreal | SingleSingle |
NuméricoNumeric | SMALLMONEYsmallmoney | DecimalDecimal |
NuméricoNumeric | moneymoney | DecimalDecimal |
Data e horaDate and Time | datedate | DatetimeDateTime |
Data e horaDate and Time | timetime | TimeSpanTimeSpan |
Data e horaDate and Time | DATETIMEdatetime | DatetimeDateTime |
Data e horaDate and Time | smalldatetimesmalldatetime | DatetimeDateTime |
Data e horaDate and Time | datetime2datetime2 | DatetimeDateTime |
Data e horaDate and Time | datetimeoffsetdatetimeoffset | DateTimeOffsetDateTimeOffset |
ExemplosExamples
a.A. Exemplo de FORMAT simplesSimple FORMAT example
O exemplo a seguir retorna uma data simples formatada para culturas diferentes.The following example returns a simple date formatted for different cultures.
DECLARE @d DATE = '11/22/2020';
SELECT FORMAT( @d, 'd', 'en-US' ) 'US English'
,FORMAT( @d, 'd', 'en-gb' ) 'Great Britain English'
,FORMAT( @d, 'd', 'de-de' ) 'German'
,FORMAT( @d, 'd', 'zh-cn' ) 'Simplified Chinese (PRC)';
SELECT FORMAT( @d, 'D', 'en-US' ) 'US English'
,FORMAT( @d, 'D', 'en-gb' ) 'Great Britain English'
,FORMAT( @d, 'D', 'de-de' ) 'German'
,FORMAT( @d, 'D', 'zh-cn' ) 'Chinese (Simplified PRC)';
Este é o conjunto de resultados.Here is the result set.
US English Great Britain English German Simplified Chinese (PRC)
---------- --------------------- ---------- ------------------------
11/22/2020 22/11/2020 22.11.2020 2020/11/22
US English Great Britain English German Chinese (Simplified PRC)
--------------------------- ---------------------- -------------------------- ---------------------------------------
Sunday, November 22, 2020 22 November 2020 Sonntag, 22. November 2020 2020年11月22日
B.B. FORMAT com cadeias de caracteres de formatação personalizadasFORMAT with custom formatting strings
O exemplo a seguir mostra os valores numéricos da formatação especificando um formato personalizado.The following example shows formatting numeric values by specifying a custom format. O exemplo supõe que a data atual é 27 de setembro de 2012.The example assumes that the current date is September 27, 2012. Para obter mais informações sobre esses e outros formatos personalizados, veja Cadeias de caracteres de formato numérico personalizado.For more information about these and other custom formats, see Custom Numeric Format Strings.
DECLARE @d DATE = GETDATE();
SELECT FORMAT( @d, 'dd/MM/yyyy', 'en-US' ) AS 'Date'
,FORMAT(123456789,'###-##-####') AS 'Custom Number';
Este é o conjunto de resultados.Here is the result set.
Date Custom Number
---------- -------------
22/11/2020 123-45-6789
C.C. FORMAT com tipos numéricosFORMAT with numeric types
O exemplo a seguir retorna 5 linhas da tabela Sales.CurrencyRate no banco de dados AdventureWorks2012AdventureWorks2012.The following example returns 5 rows from the Sales.CurrencyRate table in the AdventureWorks2012AdventureWorks2012 database. A coluna EndOfDateRate é armazenada como o tipo money na tabela.The column EndOfDateRate is stored as type money in the table. Neste exemplo, a coluna é retornada sem formatação e formatada com a especificação do formato de número .NET, o formato Geral e os tipos de formato de Moeda.In this example, the column is returned unformatted and then formatted by specifying the .NET Number format, General format, and Currency format types. Para obter mais informações sobre esses e outros formatos numéricos, veja Cadeias de caracteres de formato numérico padrão.For more information about these and other numeric formats, see Standard Numeric Format Strings.
SELECT TOP(5) CurrencyRateID, EndOfDayRate
,FORMAT(EndOfDayRate, 'N', 'en-us') AS 'Number Format'
,FORMAT(EndOfDayRate, 'G', 'en-us') AS 'General Format'
,FORMAT(EndOfDayRate, 'C', 'en-us') AS 'Currency Format'
FROM Sales.CurrencyRate
ORDER BY CurrencyRateID;
Este é o conjunto de resultados.Here is the result set.
CurrencyRateID EndOfDayRate Numeric Format General Format Currency Format
-------------- ------------ -------------- -------------- ---------------
1 1.0002 1.00 1.0002 $1.00
2 1.55 1.55 1.5500 $1.55
3 1.9419 1.94 1.9419 $1.94
4 1.4683 1.47 1.4683 $1.47
5 8.2784 8.28 8.2784 $8.28
Este exemplo especifica a cultura alemã (de-de).This example specifies the German culture (de-de).
SELECT TOP(5) CurrencyRateID, EndOfDayRate
,FORMAT(EndOfDayRate, 'N', 'de-de') AS 'Numeric Format'
,FORMAT(EndOfDayRate, 'G', 'de-de') AS 'General Format'
,FORMAT(EndOfDayRate, 'C', 'de-de') AS 'Currency Format'
FROM Sales.CurrencyRate
ORDER BY CurrencyRateID;
CurrencyRateID EndOfDayRate Numeric Format General Format Currency Format
-------------- ------------ -------------- -------------- ---------------
1 1.0002 1,00 1,0002 1,00 €
2 1.55 1,55 1,5500 1,55 €
3 1.9419 1,94 1,9419 1,94 €
4 1.4683 1,47 1,4683 1,47 €
5 8.2784 8,28 8,2784 8,28 €
D.D. FORMAT com tipos de dados de tempoFORMAT with time data types
FORMAT retorna NULL nesses casos, porque .
e :
não são ignorados.FORMAT returns NULL in these cases because .
and :
are not escaped.
SELECT FORMAT(cast('07:35' as time), N'hh.mm'); --> returns NULL
SELECT FORMAT(cast('07:35' as time), N'hh:mm'); --> returns NULL
Format retorna uma cadeia de caracteres formatada porque .
e :
são ignorados.Format returns a formatted string because the .
and :
are escaped.
SELECT FORMAT(cast('07:35' as time), N'hh\.mm'); --> returns 07.35
SELECT FORMAT(cast('07:35' as time), N'hh\:mm'); --> returns 07:35
Format retorna uma hora atual formatada com AM ou PM especificadoFormat returns a formatted current time with AM or PM specified
SELECT FORMAT(SYSDATETIME(), N'hh:mm tt'); -- returns 03:46 PM
SELECT FORMAT(SYSDATETIME(), N'hh:mm t'); -- returns 03:46 P
Format retorna a hora especificada, exibindo AMFormat returns the specified time, displaying AM
select FORMAT(CAST('2018-01-01 01:00' AS datetime2), N'hh:mm tt') -- returns 01:00 AM
select FORMAT(CAST('2018-01-01 01:00' AS datetime2), N'hh:mm t') -- returns 01:00 A
Format retorna a hora especificada, exibindo PMFormat returns the specified time, displaying PM
select FORMAT(CAST('2018-01-01 14:00' AS datetime2), N'hh:mm tt') -- returns 02:00 PM
select FORMAT(CAST('2018-01-01 14:00' AS datetime2), N'hh:mm t') -- returns 02:00 P
Format retorna a hora especificada em formato 24 hFormat returns the specified time in 24h format
select FORMAT(CAST('2018-01-01 14:00' AS datetime2), N'HH:mm') -- returns 14:00