Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Perché l'istruzione SqlServer select seleziona le righe che corrispondono e le righe che corrispondono e hanno spazi finali

Per rielaborare la mia risposta, LEN() non è sicuro testare ANSI_PADDING poiché è definito per restituire la lunghezza escludendo gli spazi finali e DATALENGTH() è preferibile come dice AdaTheDev.

La cosa interessante è che ANSI_PADDING è un'impostazione del tempo di inserimento e che è rispettata per VARCHAR ma non per NVARCHAR.

In secondo luogo, se si restituisce una colonna con spazi finali o si utilizza '=' per l'uguaglianza, sembra che si verifichi un troncamento implicito dello spazio finale.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[TestFeature1](
[Id] [varchar](50) NOT NULL,
[Leng] [decimal](18, 0) NOT NULL
) ON [PRIMARY]

GO

insert into TestFeature1 (id,leng) values ('1',100); insert into TestFeature1 (id,leng) values ('1 ',1000);

-- verify no spaces inserted at end
select '['+id+']', * from TestFeature1
select datalength(id), * from TestFeature1
go

DROP TABLE [dbo].[TestFeature1]
go
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[TestFeature1](
[Id] [nvarchar](50) NOT NULL,
[Leng] [decimal](18, 0) NOT NULL
) ON [PRIMARY]

GO

insert into TestFeature1 (id,leng) values ('1',100); insert into TestFeature1 (id,leng) values ('1 ',1000);

-- verify spaces inserted at end, and ANSI_PADDING OFF was not honoured by NVARCHAR
select '['+id+']', * from TestFeature1
select datalength(id), * from TestFeature1
go