这是新手,非常困难!我正在尝试使用以下代码从目录将图像加载到数据库中。
当我执行SP时,我得到以下表格,包括我所包含的印刷语句;
USE [store]
GO
DROP PROCEDURE [dbo].[insert2img]
/****** Object: StoredProcedure [dbo].[insert2img] Script Date: 07/08/2009 15:36:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROC [dbo].[insert2img]
as
Begin
Declare @img1 as varbinary(max)
Declare @dircmd as varchar(max)
DECLARE @filename varchar(100)
DECLARE @filepath varchar(100)
DECLARE @maxRowID int
DECLARE @count int
DECLARE @tempXMLFileName table (RowId int identity(1,1), name varchar(100))
Declare @sql as varchar(max)
Set @count = 1
Set @dircmd = 'MASTER..XP_CMDSHELL "dir/b '+ 'C:\Images\*.*"'
INSERT
@tempXMLFileName exec (@dircmd)
SET @maxRowID = (SELECT max(RowId) FROM @tempXMLFileName)
WHILE @count <= @maxRowID
BEGIN
SET @filename = (SELECT name FROM @tempXMLFileName WHERE [RowId] = @count)
Print @filepath
Set @filepath = 'C:\Images\'+@filename
Set @sql = 'Insert into dbo.aaaimg (sno,imgdate,imgname,img)
Select '' @count'',getdate(),''Image'',
BulkColumn from Openrowset(Bulk ''' + @filepath + ''',Single_Blob) as tt '
print @sql
Print @count
Exec (@sql)
Set @filepath=' '
print @filepath
Set @count = @count + 1
end
end
下面列出了使用一些打印语句执行SP时的输出;
Insert into dbo.aaaimg (sno,imgdate,imgname,img)
Select ' @count',getdate(),'Image',
BulkColumn from Openrowset(Bulk 'C:\Images\n0501.jpg', Single_Blob) as tt
1
(1 row(s) affected)
我的问题是我试图将@count的值插入到db中,但是我最终得到了db中的实际单词@count而不是值。我认为这是与分隔符有关,但我不能正确组合。
谢谢,
詹姆斯。
答案 0 :(得分:1)
您需要将@count变量连接到@sql变量,如下所示:
Set @sql = 'Insert into dbo.aaaimg (sno,imgdate,imgname,img)
Select ' + CAST(@count AS VARCHAR) + ',getdate(),''Image'',
BulkColumn from Openrowset(Bulk ''' + @filepath + ''',Single_Blob) as tt '
话虽如此,我已经提出不建议在SQL Server本身存储图像的观点。最好在db中存储图像的路径而不是图像本身。