Inserting Image from hard disk into SQL Server in while loop
-
15-06-2021 - |
题
I have some photos in specific drive on a hard disk, these photos all have a *.jpg
extension and numeric name.
For example : 1.jpg , 2.jpg , 5.jpg , ...
I'm trying to insert these photos into a table with this schema:
CREATE TABLE Employees
(
Id int NOT NULL,
Photo varbinary(max)NULL
)
At first step, I don't know what's wrong with this :
DECLARE @i INT
SET @i = 1
WHILE (@i <=100)
BEGIN
INSERT INTO Employees (Id, Photo)
SELECT @i, BulkColumn
FROM Openrowset( Bulk 'C:\Pictures\'+convert(nvarchar(5),@i)+'.jpg', Single_Blob) as EmployeePicture
SET @i = @i + 1
END
GO
Because I get an error:
Incorrect syntax near '+'
解决方案
The 'data_file' argument of OPENROWSET(BULK ... ) must be a quoted string literal, it cannot be a variable or an expression. You'll have to use dynamic sql, I fear.
DECLARE @i INT
SET @i = 1
WHILE (@i <=100)
BEGIN
DECLARE @SQL VARCHAR(MAX)
SELECT @SQL = 'INSERT INTO Employees (Id, Photo)
SELECT ' + convert(nvarchar(5), @i) + ', BulkColumn FROM OpenRowSet ( Bulk ''C:\Pictures\' +
convert(nvarchar(5), @i) + '.jpg'', Single_Blob) as EmployeePicture'
exec (@SQL)
SET @i = @i + 1
END
GO
不隶属于 StackOverflow