NEWID()SQL Server使用过程

时间:2014-12-22 21:56:33

标签: sql-server northwind

我使用NORTHWIND数据库,我必须使用在dbo.Customers中插入新值的过程。

IF OBJECT_ID('dbo.usp_InsertCustomer') IS NOT NULL
    DROP PROC dbo.usp_InsertCustomer;
GO
CREATE PROC dbo.usp_InsertCustomer
    @CompanyName AS nvarchar(40), 
    @ContactName AS nvarchar(30) = NULL,
    @ContactTitle AS nvarchar(30) = NULL,
    @Address AS nvarchar(60) = NULL,
    @City AS nvarchar(15) = NULL,
    @Region AS nvarchar(15) = NULL,
    @PostalCode AS nvarchar(10) = NULL,
    @Country AS nvarchar(15) = NULL,
    @Phone AS nvarchar(24) = NULL,
    @Fax AS nvarchar(24) = NULL
AS
BEGIN
    INSERT INTO dbo.Customers(CustomerID, CompanyName, ContactName, ContactTitle,
        Address, City, Region, PostalCode, Country, Phone, Fax)
    VALUES (NEWID(), @CompanyName, @ContactName, @ContactTitle, @Address, @City,
         @Region, @PostalCode, @Country, @Phone, @Fax);
END
GO

当我尝试使用此程序时

EXEC dbo.usp_InsertCustomer @CompanyName = N'MyCompany'

我得到了

Arithmetic overflow error converting expression to data type nvarchar.

2 个答案:

答案 0 :(得分:1)

假设你有一个围绕互联网的Northwind数据库,CustomerID期望值为nchar(5),而NEWID()将返回一个uniqueidentifier。尝试更改此项,以便您可以将正确的值插入CustomerID。

编辑:

这是生成自动ID的非常糟糕的方法,但对于您的情况,您可以执行以下操作:

(SELECT MAX(CONVERT(INT, ISNULL(CustomerID, '0'))) + 1 FROM dbo.Customers)

这假设所有CustomerID值都是表中的整数。

最好的方法是Sean Lange在评论中提到:将IDENTITY属性添加到CustomerID列(为此,您需要将数据类型更改为INT),并让SQL SERVER处理自动增量

答案 1 :(得分:0)

DECLARE @CustomerID uniqueidentifier
SET @CustomerID = NEWID()
SELECT SUBSTRING(CAST(@CustomerID AS NVARCHAR(36)),0,5)

这有帮助。