AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 196015
Accepted
John K. N.
John K. N.
Asked: 2018-01-24 06:18:27 +0800 CST2018-01-24 06:18:27 +0800 CST 2018-01-24 06:18:27 +0800 CST

A função PARSENAME() é o oposto de QUOTENAME()

  • 772

Na pergunta Existe alguma função interna (oculta) no MS-SQL para retirar as aspas de nomes de objetos? o autor estava procurando conselhos sobre se havia uma função interna para "UNQUOTE" uma string entre aspas. O autor McNets havia notado que algumas funções internas podiam lidar com valores de parâmetros entre aspas (eg [MyTable]) e sem aspas (eg ) MyTablepassados ​​(eg OBJECT_ID()).

Na resposta ( 1 ) dada por David Browne - Microsoft foi feita a citação que:

...o inverso de QUOTENAME é PARSENAME, que tem a capacidade adicional de navegar por nomes de várias partes.

Eu discordei desta parte da resposta com o seguinte comentário:

Concordo que você pode modificar um argumento passado para PARSENAME()exibir as partes de um identificador de várias partes, seja SERVER, DATABASE, SCHEMAou OBJECTpart. Mas IMHO afirmando que PARSENAMEé o oposto de QUOTENAMEé um pouco exagerado.

Minha pergunta agora é:

A função é PARSENAME()o oposto de QUOTENAME()?

sql-server functions
  • 1 1 respostas
  • 2080 Views

1 respostas

  • Voted
  1. Best Answer
    John K. N.
    2018-01-24T06:18:27+08:002018-01-24T06:18:27+08:00

    Baseado no comentário de ypercubeᵀᴹ que diz:

    ...você pode encontrar uma string xque parsename(quotename(x),1)seja diferente de x? Se não, isso se enquadra na definição de "função inversa" ;) ...

    ... Criei uma instrução simples para dar uma olhada nos diferentes valores retornados por essas funções. O código é o seguinte:

    Código

    DECLARE 
    -- Text that I will be converting using QUOTENAME()
    @Text2Quote_1 AS NVARCHAR(20),
    @Text2Quote_2 AS NVARCHAR(20),
    @Text2Quote_3 AS NVARCHAR(20),
    @Text2Quote_4 AS NVARCHAR(20),
    -- The characters used for "quotation"
    @QuoteChar_1 AS NCHAR(1),
    @QuoteChar_2 AS NCHAR(1),
    @QuoteChar_3 AS NCHAR(1),
    -- The Parsing option as defined in the original MS documnenation for PARSSENAME()
    @ParseParam AS INT
    
    SET @Text2Quote_1 = N'Test'
    SET @Text2Quote_2 = N'[Test]'
    SET @Text2Quote_3 = N'Test.dbo.test'
    SET @Text2Quote_4 = N'[Test].[dbo].[test]'
    
    SET @QuoteChar_1 = ''''
    SET @QuoteChar_2 = '[' 
    SET @QuoteChar_3 = '"' 
    
    SET @ParseParam = 1 -- Parsing level : Object name
    -- checking the results for ' single quotes
    SELECT  @Text2Quote_1 AS OriginalText_1,
            @Text2Quote_2 AS OriginalText_2,
            @Text2Quote_3 AS OriginalText_3,
            @Text2Quote_4 AS OriginalText_4
    SELECT  QUOTENAME(@Text2Quote_1,@QuoteChar_1) AS QuotedText_1, 
            QUOTENAME(@Text2Quote_2,@QuoteChar_1) AS QuotedText_2, 
            QUOTENAME(@Text2Quote_3,@QuoteChar_1) AS QuotedText_3, 
            QUOTENAME(@Text2Quote_4,@QuoteChar_1) AS QuotedText_4
    select  PARSENAME(QUOTENAME(@Text2Quote_1,@QuoteChar_1),@ParseParam) AS Parsed_QuotedText_1, 
            PARSENAME(QUOTENAME(@Text2Quote_2,@QuoteChar_1),@ParseParam) AS Parsed_QuotedText_2,
            PARSENAME(QUOTENAME(@Text2Quote_3,@QuoteChar_1),@ParseParam) AS Parsed_QuotedText_3,
            PARSENAME(QUOTENAME(@Text2Quote_4,@QuoteChar_1),@ParseParam) AS Parsed_QuotedText_4
    

    Basicamente, defino valores de string, produzo esse valor QUOTENAME()e produzo o valor, depois PARSENAME()o QUOTENAME()valor ed e o produzo.

    Resultados

    Os resultados foram bastante interessantes:

    OriginalText_1           OriginalText_2           OriginalText_3           OriginalText_4          
    ------------------------ ------------------------ ------------------------ ------------------------
    Test                     [Test]                   Test.dbo.test            [Test].[dbo].[test]     
    
    (1 row(s) affected)                                                                                
    
    QuotedText_1             QuotedText_2             QuotedText_3             QuotedText_4            
    ------------------------ ------------------------ ------------------------ ------------------------
    'Test'                   '[Test]'                 'Test.dbo.test'          '[Test].[dbo].[test]'   
    
    (1 row(s) affected)                                                                                
    
    Parsed_QuotedText_1      Parsed_QuotedText_2      Parsed_QuotedText_3      Parsed_QuotedText_4     
    ------------------------ ------------------------ ------------------------ ------------------------
    'Test'                   NULL                     test'                    NULL                    
    
    (1 row(s) affected)                                                                                
    

    Quando o texto base Test.dbo.test( OriginalText_3 ) é passado para a QUOTENAME()função, ele é convertido em: 'Test.dbo.test'( QuotedText_3 )

    Quando a string QuotedText_3'Test.dbo.test' é passada para a PARSENAME()função, ela é convertida em: test'( Parsed_QuotedText_3 )

    Conclusão

    Visto que provei a tese de ypercubeᵀᴹ errada, acho que é seguro afirmar que a função PARSENAME()não é a inversa de QUOTENAME().


    Com base no feedback de Aaron Bertrand aqui o código para colchetes (adicionar ao script original)[ ]

    Código adicional para colchetes[ ]

    -- checking the results for [ brackets                                                                           
    SELECT  @Text2Quote_1 AS OriginalText_1,                                                                         
            @Text2Quote_2 AS OriginalText_2,                                                                         
            @Text2Quote_3 AS OriginalText_3,                                                                         
            @Text2Quote_4 AS OriginalText_4                                                                          
    SELECT  QUOTENAME(@Text2Quote_1,@QuoteChar_2) AS QuotedText_1,                             
            QUOTENAME(@Text2Quote_2,@QuoteChar_2) AS QuotedText_2,                             
            QUOTENAME(@Text2Quote_3,@QuoteChar_2) AS QuotedText_3,                             
            QUOTENAME(@Text2Quote_4,@QuoteChar_2) AS QuotedText_4                              
    select  PARSENAME(QUOTENAME(@Text2Quote_1,@QuoteChar_2),@ParseParam) AS Parsed_QuotedText_1,
            PARSENAME(QUOTENAME(@Text2Quote_2,@QuoteChar_2),@ParseParam) AS Parsed_QuotedText_2,
            PARSENAME(QUOTENAME(@Text2Quote_3,@QuoteChar_2),@ParseParam) AS Parsed_QuotedText_3,
            PARSENAME(QUOTENAME(@Text2Quote_4,@QuoteChar_2),@ParseParam) AS Parsed_QuotedText_4
    

    Saída para colchetes[ ]

    OriginalText_1           OriginalText_2           OriginalText_3           OriginalText_4
    ------------------------ ------------------------ ------------------------ ------------------------
    Test                     [Test]                   Test.dbo.test            [Test].[dbo].[test]
    
    (1 row(s) affected)
    
    QuotedText_1             QuotedText_2             QuotedText_3             QuotedText_4
    ------------------------ ------------------------ ------------------------ ------------------------
    [Test]                   [[Test]]]                [Test.dbo.test]          [[Test]].[dbo]].[test]]]
    
    (1 row(s) affected)
    
    Parsed_QuotedText_1      Parsed_QuotedText_2      Parsed_QuotedText_3      Parsed_QuotedText_4
    ------------------------ ------------------------ ------------------------ ------------------------
    Test                     [Test]                   Test.dbo.test            [Test].[dbo].[test]
    
    (1 row(s) affected)
    

    e para completar as coisas o código para as aspas duplas

    Código adicional para aspas duplas"

    -- checking the results for [ brackets                                                                           
    SELECT  @Text2Quote_1 AS OriginalText_1,                                                                         
            @Text2Quote_2 AS OriginalText_2,                                                                         
            @Text2Quote_3 AS OriginalText_3,                                                                         
            @Text2Quote_4 AS OriginalText_4                                                                          
    SELECT  QUOTENAME(@Text2Quote_1,@QuoteChar_3) AS QuotedText_1,                             
            QUOTENAME(@Text2Quote_2,@QuoteChar_3) AS QuotedText_2,                             
            QUOTENAME(@Text2Quote_3,@QuoteChar_3) AS QuotedText_3,                             
            QUOTENAME(@Text2Quote_4,@QuoteChar_3) AS QuotedText_4                              
    select  PARSENAME(QUOTENAME(@Text2Quote_1,@QuoteChar_3),@ParseParam) AS Parsed_QuotedText_1,
            PARSENAME(QUOTENAME(@Text2Quote_2,@QuoteChar_3),@ParseParam) AS Parsed_QuotedText_2,
            PARSENAME(QUOTENAME(@Text2Quote_3,@QuoteChar_3),@ParseParam) AS Parsed_QuotedText_3,
            PARSENAME(QUOTENAME(@Text2Quote_4,@QuoteChar_3),@ParseParam) AS Parsed_QuotedText_4
    

    Saída para aspas duplas"

    OriginalText_1           OriginalText_2           OriginalText_3           OriginalText_4
    ------------------------ ------------------------ ------------------------ ------------------------
    Test                     [Test]                   Test.dbo.test            [Test].[dbo].[test]
    
    (1 row(s) affected)
    
    QuotedText_1             QuotedText_2             QuotedText_3             QuotedText_4
    ------------------------ ------------------------ ------------------------ ------------------------
    "Test"                   "[Test]"                 "Test.dbo.test"          "[Test].[dbo].[test]"
    
    (1 row(s) affected)
    
    Parsed_QuotedText_1      Parsed_QuotedText_2      Parsed_QuotedText_3      Parsed_QuotedText_4
    ------------------------ ------------------------ ------------------------ ------------------------
    Test                     [Test]                   Test.dbo.test            [Test].[dbo].[test]
    
    (1 row(s) affected)
    

    Com base no feedback do ypercube™ e no novo feedback de Aaron Bertrand , chegamos a uma conclusão mútua

    PARSENAME()é o inverso de QUOTENAME()se as seguintes condições forem atendidas:

    PARSENAME(x,1)-1(QUOTENAME(x,q))onde q={1,2}ex='{'any_string_value'}


    Referências:

    • PARSENAME (Transact SQL) (Microsoft Docs)
    • QUOTENAME (Transact SQL) (Microsoft Docs)
    • 6

relate perguntas

  • SQL Server - Como as páginas de dados são armazenadas ao usar um índice clusterizado

  • Preciso de índices separados para cada tipo de consulta ou um índice de várias colunas funcionará?

  • Quando devo usar uma restrição exclusiva em vez de um índice exclusivo?

  • Quais são as principais causas de deadlocks e podem ser evitadas?

  • Como determinar se um Índice é necessário ou necessário

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve