2014-02-18 37 views
0

我有一個這樣的表,但不只是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之外的相同值。我可以這樣做,但是列數太多(或者我只是懶惰)。什麼是正確的方法來做到這一點?

+0

你知道有像IDENTITY插入ID的東西? http://msdn.microsoft.com/en-us/library/ms186775.aspx – NickyvV

回答

1

我懷疑你的ID已被設置爲其真實的身份。此代碼可能適用於您。

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 
+0

你是一個天才。 :o –