我需要一个用户定义的函数来插入新记录并返回Id,这是可能的,我该怎么做?
我尝试使用insert语句创建一个函数,但是我收到以下错误:
Invalid use of the side-affecting operator 'INSERT' within a function.
我正在使用SQL Server 2008。
更新SQL:
CREATE FUNCTION dbo.GetNewBookingReference()
RETURNS int
AS
BEGIN
INSERT INTO BookingReference
(CreatedTime, CreatedByUserId)
VALUES
(GETDATE()
,10)
RETURN @@IDENTITY
END
由于
答案 0 :(得分:8)
在SQL Server中,用户定义的函数无法更改数据库状态。您必须使用带有OUTPUT
参数的存储过程。
答案 1 :(得分:0)
insert into table1(name, age) values('xyz', 2);
select SCOPE_IDENTITY() as NewID;
答案 2 :(得分:0)
// Check if new identity is needed.
if (getId)
{
// Execute db specific autonumber or identity retrieval code
// SELECT SCOPE_IDENTITY() -- for SQL Server
// SELECT @@IDENTITY -- for MS Access
// SELECT MySequence.NEXTVAL FROM DUAL -- for Oracle
string identitySelect;
switch (DataProvider)
{
// Access
case "System.Data.OleDb":
identitySelect = "SELECT @@IDENTITY";
break;
// Sql Server
case "System.Data.SqlClient":
identitySelect = "SELECT SCOPE_IDENTITY()";
break;
// Oracle
case "System.Data.OracleClient":
identitySelect = "SELECT MySequence.NEXTVAL FROM DUAL";
break;
default:
identitySelect = "SELECT @@IDENTITY";
break;
}
command.CommandText = identitySelect;
id = int.Parse(command.ExecuteScalar().ToString());
}