将计算列强制为int

时间:2016-11-11 21:11:42

标签: sql sql-server tsql

我将这个用[TankNumId]创建的表作为计算列。

如何将数据类型强制为int。它保持设置为nvarchar,这是列[TankNum]的数据类型。

[TankNum]列中的值为100-1, 100-2 100-3, etc。因此,为什么我使用计算列来转换' - '到'。'这样它就可以成为[TankNumId]列中的有效int。有什么建议?

CREATE TABLE [dbo].[tblTank9](
[Id] [int] IDENTITY(1,1) NOT NULL,
[TankNumId]  AS (replace([TankNum],'-','.' )) PERSISTED NOT NULL,
[TankNum] [nvarchar](10) NULL,
[CompanyName] [nvarchar](30) NULL,
[Ft] [float] NULL,
[Inch] [float] NULL,
[HFt] [smallint] NULL,
[HIn] [smallint] NULL,
[HFx] [smallint] NULL,
[GaPt] [char](100) NULL,
 CONSTRAINT [PK_tblTank9] PRIMARY KEY CLUSTERED 
(
[TankNumId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

1 个答案:

答案 0 :(得分:1)

replace 函数接收nvarchar并返回nvarchar

您需要CAST或CONVERT您的结果才能浮动,因为100.1不是整数

SELECT CAST(YourVarcharCol AS float) FROM Table
SELECT CONVERT(float, YourVarcharCol) FROM Table