Create function Fun_Auto_Insert()
returns nchar(3)
as
BEGIN
DECLARE @Seat_No NCHAR(3) = 'A1'
declare @Name CHAR(30)
declare @Contact_No INT
declare @Row_No INT
declare @Row_ID CHAR(1)
declare @ASCII_No INT
declare @CHAR_ID CHAR
IF (SELECT count(*) FROM MOVIE_TICKETS) = 0
BEGIN
RETURN @Seat_No
END
ELSE
SELECT @Seat_No= MAX(SEAT_NO) FROM MOVIE_TICKETS
SELECT @Row_No=SUBSTRING( @Seat_No,2,LEN(@Seat_No)-1) FROM MOVIE_TICKETS
IF @Row_No=12
BEGIN
SET @Row_ID=SUBSTRING(@Seat_No,1,1)
--convert to ASCII NO
SET @ASCII_No=ASCII(@Row_ID)
SET @ASCII_No=@ASCII_No+1
--convert to CHAR
SET @CHAR_ID=CHAR(@ASCII_No)
SET @Row_No=1
SET @Seat_No=CONCAT(@CHAR_ID,@Row_No)
RETURN @Seat_No
END
ELSE
SET @Row_No=@Row_No+1
SET @Row_ID=SUBSTRING(@Seat_No,1,1)
SET @Seat_No=CONCAT(@Row_ID,@Row_No)
RETURN @Seat_No
END
GO
但不幸的是我的逻辑失败了。它在A10之后显示SEAT_NO A10,如下所示。但是在A10之后我想要A11。
任何人都可以帮助我获得我想要的输出a1,a2 ..... a12,b1,b2 ..... b12,c1 ...... z12。
SEAT_NO CONTACT_NO NAME
A1 8444 BHARATH
A2 8444 BHARATH
A3 8444 BHARATH
A4 8444 BHARATH
A5 8444 BHARATH
A6 8444 BHARATH
A7 8444 BHARATH
A8 8444 BHARATH
A9 8444 BHARATH
A10 8444 BHARATH
A10 8444 BHARATH
A10 8444 BHARATH
A10 8444 BHARATH
A10 8444 BHARATH
答案 0 :(得分:0)
我会重写整个函数并废弃所有这些字符串操作,见下文:
Create function Fun_Auto_Insert()
returns nchar(3)
as
BEGIN
DECLARE @Seat_No NCHAR(3);
;WITH CTE AS
(SELECT Alphas+vals AS SEAT_NO
,Alphas
,vals
FROM (
select CHAR(number) Alphas
from master..spt_values
WHERE number >= 65 and number <= 90
GROUP BY number) A
CROSS APPLY (VALUES ('1'),('2'),('3'),('4')
,('5'),('6'),('7'),('8')
,('9'),('10'),('11'),('12'))C(vals)
)
SELECT TOP 1 @Seat_No = SEAT_NO
FROM CTE C
WHERE NOT EXISTS (SELECT 1
FROM MOVIE_TICKETS
WHERE C.SEAT_NO = Seat_No)
ORDER BY Alphas ASC , CAST(vals AS INT) ASC
RETURN @Seat_No;
END
GO
CREATE TABLE MOVIE_TICKETS(Seat_No VARCHAR(3))
GO
INSERT INTO MOVIE_TICKETS VALUES ('A2'), ('A10'), ('B2')
GO
SELECT dbo.Fun_Auto_Insert()
GO
A1