插入除某些列以外的相同行值

时间:2014-02-18 08:36:35

标签: sql-server database sql-server-2008 stored-procedures

我有一个这样的表,但不只是5列(可能大于10)

ID  |   FileName    |   Type    |   Other1  |   Other 2 
1       image1.eps      3           assff       12321
2       image2.eps      3           asdfs       12321
3       image3.eps      3           asdaf       24124

这样的查询:

DECLARE @FileName NVARCHAR(2000)
SET @FileName = 'image1.eps'

INSERT INTO DigitalAssets
VALUES(
    (SELECT max(ID)+1 FROM DigitalAssets)
    ,(SUBSTRING(@FileName,0,LEN(@FileName)-4)+'.jpg')
    ,(1)
    ,(SELECT TOP 1 Other1 FROM DigitalAssets WHERE FileName = @FileName )
    ,(SELECT TOP 1 Other2 FROM DigitalAssets WHERE FileName = @FileName )
)

现在我想创建一个存储过程,它将插入除id, filename, and type之外的相同值。我可以这样做,但有太多列(或者我只是懒惰)。这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

我怀疑你的身份证已被设置为真。此代码可能适合您。

DECLARE @FileName NVARCHAR(2000)
SET @FileName = 'image1.eps'

INSERT INTO DigitalAssets([FileName], Type, Other1, Other2) 
SELECT SUBSTRING(@FileName,0,LEN(@FileName)-4)+'.jpg',1, Other1, Other2 
FROM DigitalAssets WHERE FileName = @FileName

如果不是,你可以试试这个。

DECLARE @FileName NVARCHAR(2000)
SET @FileName = 'image1.eps'

INSERT INTO DigitalAssets(id, [FileName], Type, Other1, Other2) 
SELECT (SELECT id
FROM DigitalAssets o1
WHERE NOT EXISTS (SELECT 1 FROM DigitalAssets o2 WHERE o2.id > o1.id)) 
SUBSTRING(@FileName,0,LEN(@FileName)-4)+'.jpg',1, Other1, Other2 
FROM DigitalAssets WHERE FileName = @FileName