DECLARE
	@UserSign INT,
	@CreateDate DATETIME,
	@Serial NVARCHAR(100),
	@ItemCode NVARCHAR(100),
	@WhsCode NVARCHAR(100),
	@BaseType INT,
	@BaseEntry INT,
	@BaseLine INT;

DECLARE serial_cursor CURSOR FOR 
	SELECT
		T0."UserSign", T0."CreateDate", T0."IntrSerial", T0."ItemCode", T3."Code", T0."BaseType", T0."BaseEntry", T0."BaseLinNum"
	FROM
		OSRI T0
	INNER JOIN
		OITM T1 ON T0."ItemCode" = T1."ItemCode"
	INNER JOIN
		OWHS T2 ON T0."WhsCode" = T2."WhsCode"
	INNER JOIN
		PMX_OSWH T3 ON T2."WhsCode" = T3."SboWhsCode"
	WHERE
		T0."Status" <> 1 
		AND T1."ManSerNum" = 'Y'
		AND T1."MngMethod" = 'A'
		AND T2."U_PMX_IMBP"='Y'
		AND NOT EXISTS (SELECT 1 FROM PMX_SENU S0 WHERE S0."ItemCode" = T0."ItemCode" AND S0."SerialNumber" = T0."IntrSerial")

	OPEN serial_cursor
	FETCH NEXT FROM serial_cursor INTO 	@UserSign, @CreateDate, @Serial, @ItemCode, @WhsCode, @BaseType, @BaseEntry, @BaseLine

	WHILE @@FETCH_STATUS = 0  
	BEGIN
		DECLARE @InternalKeyTable TABLE ("InternalKey" int)

		INSERT INTO PMX_SENU ("Canceled", "UserSign", "CreateDateTime", "UpdateDateTime", "Version", "SerialNumber", "InStock", "ItriKey", "ItemCode", "LUID", "PmxWhsCode") 
		OUTPUT INSERTED."InternalKey" INTO @InternalKeyTable
		SELECT 'N', @UserSign, @CreateDate, @CreateDate, 1, @Serial, 1, NULL, @ItemCode, NULL, @WhsCode;

		INSERT INTO PMX_SELD ( "Canceled", "UserSign", "CreateDateTime", "UpdateDateTime", "Version", "SerialKey", "BaseType", "BaseEntry", "BaseLine") 
		SELECT 'N', @UserSign, @CreateDate, @CreateDate, 1, "InternalKey", @BaseType, @BaseEntry, @BaseLine FROM @InternalKeyTable

		FETCH NEXT FROM serial_cursor INTO @UserSign, @CreateDate, @Serial, @ItemCode, @WhsCode, @BaseType, @BaseEntry, @BaseLine
	END 
	CLOSE serial_cursor
	DEALLOCATE serial_cursor
