2

我有下表SQL Server

 CREATE TABLE [dbo].[tblTempPo](
    [TempPoID] [int] IDENTITY(1,1) NOT NULL,
    [guid]  AS ([dbo].[GetIdentity]()),
    [Qty] [int] NULL,
    [MobileBrandID] [int] NULL,
    [MobileID] [int] NULL
)

每次添加新行时,我都需要insert当前列。我尝试使用以下内容,但没有按预期工作:row numberguidfunction

ALTER FUNCTION GetIdentity() 
RETURNS INT AS
BEGIN
   RETURN (SELECT top 1 ROW_NUMBER() OVER(ORDER BY TempPoID asc)FROM tblTempPo)
END
4

3 回答 3

1

您的函数GetIdentity()可能总是返回 1 但这不是确定的事情,因为您使用的是select top 1...不带order by子句的。
如果您想要返回的最高值,则row_number()需要添加order by 1 desc与做SELECT count(*) from tblTempPo.

像这样修复GetIdentity()对您的情况没有多大帮助,因为[guid] AS ([dbo].[GetIdentity]())会给您一个计算列,每次查询表时都会评估该列,而不是插入新行时。对于所有行,您将始终具有相同的值。

您可以使用将TempPoID用作参数的函数作为计算列

CREATE FUNCTION GetIdentity(@P int) 
RETURNS INT AS
BEGIN
   RETURN (SELECT rn
           FROM (SELECT TempPoID,
                        ROW_NUMBER() OVER(ORDER BY TempPoID ASC) AS rn
                 FROM tblTempPo) AS T
           WHERE TempPoID = @P)
END

表定义:

CREATE TABLE [dbo].[tblTempPo](
    [TempPoID] [int] IDENTITY(1,1) NOT NULL primary key,
    [guid] as dbo.GetIdentity(TempPoID),
    [Qty] [int] NULL,
    [MobileBrandID] [int] NULL,
    [MobileID] [int] NULL

我从来没有使用过这个,所以我不能告诉你这是否是一件好事。这可能对您的查询性能造成毁灭性影响,我只是不知道。

于 2012-01-25T09:57:10.507 回答
0

我同意评论,您应该更改 GUID 列名。如果您确实必须存储该TempPoID列两次,请使用计算列。例子:

CREATE TABLE #tblTempPo (
    [TempPoID] [int] IDENTITY(1,1) NOT NULL,
    [second_id] AS TempPoID,
    [Qty] [int] NULL,
    [MobileBrandID] [int] NULL,
    [MobileID] [int] NULL
)

INSERT INTO #tblTempPo (Qty, MobileBrandID, MobileID) VALUES 
(10, 10, 15), (20, 23, 45), (55, 23, 12), (10, 1, 1)

SELECT * FROM #tblTempPo

DROP TABLE #tblTempPo

如果您需要更复杂的方法 - 使用触发器。

于 2012-01-25T09:05:51.797 回答
0

这不是一个好主意,但如果你真的需要它,试试触发器:

create table [dbo].[tblTempPo](
[TempPoID] [int] identity(1,1) NOT NULL,
[guid]  int,
[Qty] [int] NULL,
[MobileBrandID] [int] NULL,
[MobileID] [int] NULL
)
go

create trigger [dbo].[tblTempPo_Trig] on [dbo].[tblTempPo] instead of insert as
declare @cnt int
select @cnt = count(*)
from [dbo].[tblTempPo] with(nolock)
insert into [dbo].[tblTempPo]([guid], [Qty], [MobileBrandID], [MobileID])
select @cnt+row_number() over (order by [TempPoID]), [Qty], [MobileBrandID], [MobileID] from inserted
go

insert into [dbo].[tblTempPo]([Qty], [MobileBrandID], [MobileID]) values (0, 0,0), (0, 0,0), (0, 0,0), (0, 0,0)
insert into [dbo].[tblTempPo]([Qty], [MobileBrandID], [MobileID]) values (0, 0,0), (0, 0,0), (0, 0,0), (0, 0,0)

select * from [dbo].[tblTempPo]

go
drop table [dbo].[tblTempPo]
go
于 2013-02-13T14:42:24.347 回答