所以这看起来应该很容易。但是说我有一个插页:
insert into TABLE VALUES ('OP','OP_DETAIL','OP_X')
我希望X从1-100开始。 (知道有一些已经存在的数字,所以如果插入失败,我希望它继续下去)
我该怎么做?
答案 0 :(得分:2)
这是一种稍快的方式
-- techniques from Jeff Moden and Itzik Ben-Gan:
;WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),
E02(N) AS (SELECT 1 FROM E00 a, E00 b),
E04(N) AS (SELECT 1 FROM E02 a, E02 b),
E08(N) AS (SELECT 1 FROM E04 a, E04 b),
cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E08)
INSERT INTO yourTable
SELECT 'OP','OP_DETAIL','OP_' + CAST(N AS varchar)
FROM cteTally
WHERE N <= 100
答案 1 :(得分:1)
无需循环。基于集合的方法FTW!
这是一个应该使用数字表的主要示例。其他的回答者在飞行中创造了相同的东西,但如果你问我,你就无法击败一张好的,老式的桌子!
使用您最好的Google-Fu查找脚本或here's one I made earlier
INSERT INTO your_table (you_should, always_list, your_columns)
SELECT 'OP'
, 'OP_DETAIL'
, 'OP_' + Cast(number As varchar(11))
FROM dbo.numbers
WHERE number BETWEEN 1 AND 100
AND NOT EXISTS (
SELECT your_columns
FROM your_table
WHERE your_columns = 'OP_' + Cast(numbers.number As varchar(11))
)
;
答案 2 :(得分:0)
CREATE TABLE #Temp (
OPCol VARCHAR(128),
OPDetailCol VARCHAR(128),
OPXCol VARCHAR(128)
)
--Add sample data, representing some random OPX values that may already exist.
INSERT INTO #Temp (OPCol, OPDetailCol, OPXCol)
VALUES
('OP','OP_DETAIL','OP_4'),
('OP','OP_DETAIL','OP_22'),
('OP','OP_DETAIL','OP_39'),
('OP','OP_DETAIL','OP_70')
--Common table expression with recursion.
;WITH CTE AS
(
SELECT 1 AS OPCounter
UNION ALL
SELECT OPCounter + 1
FROM CTE
WHERE OPCounter < 100
)
INSERT INTO #Temp (OPCol, OPDetailCol, OPXCol)
SELECT 'OP','OP_DETAIL','OP_' + CAST(OPCounter AS VARCHAR(3))
FROM CTE
WHERE NOT EXISTS (
SELECT 1
FROM #Temp t
WHERE t.[OPXCol] = 'OP_' + CAST(OPCounter AS VARCHAR(3))
)
--Verify results
SELECT * FROM #Temp