1、查询 itemList表.
SELECT * FROM dbo.itemList
如图:
<图一>
itemList 共有 28条数据
现在我要实现,从excel数据导入itemList这个表,要求 itemId 里面的值 符合P*********格式,并且是接着递增,如在新增应为P000000029,
但是这个itemId是程序生成的,如何在插入时候自动生成,P000000030,P000000031...格式呢。
1、将excel数据格式导入数据库,这时候生成表 temp.
2、查询temp表,查询出来的结果集符合itemList现有数据如下:
SELECT *
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY itemId ) AS number ,
*
FROM dbo.temp
) t
注:其中 number为行号。
<图二>
将图二的数据插入itemList,如下sql
INSERT INTO [electrolux].[dbo].[itemList]
([itemId]
,[itemName]
,[itemGroup]
,[stdPrice]
,[splPrice]
,[imageSrc]
,[status]
,[orgId]
,[orgName]
,[remark]
,[creator]
,[createDate]
,[lastUpdator]
,[lastUpdate]
,[endDate]
,[limitCount]
,[totalCount]
,[packageGiftName])
SELECT dbo.fn_GetProductId(( ROW_NUMBER() OVER ( ORDER BY [Model] ) )) AS itemId,
[Model] AS itemName ,
‘‘ AS itemGroup ,
[Retail Price (RMB)] AS stdPrice ,
[Price Offer(RMB)] AS splPrice ,
‘‘ AS imageSrc ,
‘Y‘ AS status ,
20 AS orgId ,
‘‘ AS orgName ,
[Product Name] AS remark ,
‘admin‘ AS creator ,
GETDATE() AS createDate ,
‘admin‘ AS lastUpdator ,
GETDATE() AS lastUpdate ,
DATEADD(mm,2,GETDATE()) AS endDate ,
NULL AS limitCount ,
NULL AS totalCount ,
‘‘ AS packageGiftName
FROM [electrolux].[dbo].[temp] ORDER BY model asc
返回特定合适的itemId函数如下:
USE [electrolux]
GO
/****** Object: UserDefinedFunction [dbo].[fn_GetProductId] Script Date: 01/15/2015 16:52:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <[email protected]>
-- Create date: <2015-01-08 10:15:46.123>
-- Description: <根据行号返回特定格式的产品ID>
-- =============================================
ALTER FUNCTION [dbo].[fn_GetProductId] ( @rowNumber INT )
RETURNS VARCHAR(100)
AS
BEGIN
DECLARE @maxId INT --最大的ID
DECLARE @maxIdText VARCHAR(100) --返回的格式
SELECT @maxId = CONVERT(INT, REPLACE(ISNULL(MAX(itemId), ‘P0‘), ‘P‘,
‘‘)) + @rowNumber
FROM dbo.itemList
SELECT @maxIdText = ‘P‘ + REPLICATE(‘0‘, 9 - LEN(@maxId))
+ CAST(@maxId AS VARCHAR)
RETURN @maxIdText
END
完毕,往往插入数据的时候,特定格式的ID可以这么来生成。