How to extract multiple image from SQL database with one query? - sql

I tried following query for export images to selective folder but it export only one file in one time but I want all image export at same time.
USE [DanfeyPhoto]
GO
/****** Object: StoredProcedure [dbo].[usp_ExportImage] Script Date: 7/31/2021 7:36:40 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----- first ma database lai sql 2014 ma restore gareko xa vane matra yo query le kam garxa.
ALTER PROCEDURE [dbo].[usp_ExportImage] (
#PicName NVARCHAR (100)
,#ImageFolderPath NVARCHAR(1000)
,#Filename NVARCHAR(1000)
)
AS
BEGIN
DECLARE #ImageData VARBINARY (max);
DECLARE #Path2OutFile NVARCHAR (2000);
DECLARE #Obj INT
set #ImageFolderPath='D:\PhotoExtract\'
SET NOCOUNT ON
SELECT #ImageData = (
SELECT convert (VARBINARY (max), photoim, 1)
FROM MemberDetail
WHERE MemberNo = #PicName
);
SET #Path2OutFile = CONCAT (
#ImageFolderPath
,'\'
, #Filename
);
BEGIN TRY
EXEC sp_OACreate 'ADODB.Stream' ,#Obj OUTPUT;
EXEC sp_OASetProperty #Obj ,'Type',1;
EXEC sp_OAMethod #Obj,'Open';
EXEC sp_OAMethod #Obj,'Write', NULL, #ImageData;
EXEC sp_OAMethod #Obj,'SaveToFile', NULL, #Path2OutFile, 2;
EXEC sp_OAMethod #Obj,'Close';
EXEC sp_OADestroy #Obj;
END TRY
BEGIN CATCH
EXEC sp_OADestroy #Obj;
END CATCH
SET NOCOUNT OFF
END
-- EXEC [dbo].[usp_ExportImage] '00001', 'D:\PhotoExtract', '00001.jpg'
-- select * from MemberDetail

Related

Saving the BLOB data to a file via OLE processes

I am trying to export data from SQL Server to a file. The data is a .jpg. I found a script that would do so however whenever i run it I get a not any error message. and file not create in folder Please help me
DECLARE xArgsEntryImg CURSOR FOR
SELECT TOP 1
CONVERT(varbinary(max), E.ENTRY_IMAGE, 1) AS img1,
CONVERT(varchar(50), E.TKT_NO) + 'IMG1.jpg' AS img,
T.TicketNo
FROM
ITNLTCS_IMAGE.dbo.ICS_ENTRY_IMAGE E
INNER JOIN
fms25.dbo.tblTagTransaction T ON E.TKT_NO = T.TicketNo
INNER JOIN
FMS25.dbo.ReqPayViolationMessage m ON (T.TagTransactionPk = m.TagTransactionPk)
WHERE
NOT EXISTS (SELECT TOP 1 1
FROM tblImgUploadLog I
WHERE ImgType = 1
AND T.TicketNo = I.TicketNo)
DECLARE #PathForEntryImg nvarchar(max);
DECLARE #ImageDataForEntryImg varbinary(max);
DECLARE #FilenameForEntryImg NVARCHAR(max);
DECLARE #TicketNoForEntryImg bigint;
OPEN xArgsEntryImg
FETCH xArgsEntryImg INTO #ImageDataForEntryImg, #FilenameForEntryImg, #TicketNoForEntryImg
WHILE ##FETCH_STATUS = 0
BEGIN
BEGIN TRY
DECLARE #FullPathToOutputFileforEntryImg NVARCHAR(max);
DECLARE #FileName varchar(4000) = 'D:\FMS\IMAGES\CURRENT\a.jpg'
DECLARE #ObjectTokenEntryImg INT
EXEC sp_OACreate 'ADODB.Stream', #ObjectTokenEntryImg OUTPUT; -- Create Object
EXEC sp_OASetProperty #ObjectTokenEntryImg, 'Type', 1;
EXEC sp_OAMethod #ObjectTokenEntryImg, 'Open';
EXEC sp_OAMethod #ObjectTokenEntryImg, 'Write', NULL, #ImageDataForEntryImg;
EXEC sp_OAMethod #ObjectTokenEntryImg, 'SaveToFile', NULL, #FileName, 2;
EXEC sp_OAMethod #ObjectTokenEntryImg, 'Close';
EXEC sp_OADestroy #ObjectTokenEntryImg;
END TRY
BEGIN CATCH
END CATCH
FETCH NEXT From xArgsEntryImg INTO #ImageDataForEntryImg, #FilenameForEntryImg, #TicketNoForEntryImg
END
CLOSE xArgsEntryImg
DEALLOCATE xArgsEntryImg

Export multiple images from image column

I have the following stored procedure, how could I modify it to export multiple images at once? A TicketID can contain several images, could the IN statement work here? Appreciate all answers!
CREATE PROCEDURE dbo.ExportImage (
#ImgName NVARCHAR (100)
,#ImageFolderPath NVARCHAR(1000)
,#Filename NVARCHAR(1000)
)
AS
BEGIN
DECLARE #ImageData VARBINARY (max);
DECLARE #Path2OutFile NVARCHAR (2000);
DECLARE #Obj INT
SET NOCOUNT ON
SELECT #ImageData = (
SELECT convert (VARBINARY (max), ImgData, 1)
FROM Images
WHERE TicketID = #ImgName
);
SET #Path2OutFile = CONCAT (
#ImageFolderPath
,'\'
, #Filename
);
BEGIN TRY
EXEC sp_OACreate 'ADODB.Stream' ,#Obj OUTPUT;
EXEC sp_OASetProperty #Obj ,'Type',1;
EXEC sp_OAMethod #Obj,'Open';
EXEC sp_OAMethod #Obj,'Write', NULL, #ImageData;
EXEC sp_OAMethod #Obj,'SaveToFile', NULL, #Path2OutFile, 2;
EXEC sp_OAMethod #Obj,'Close';
EXEC sp_OADestroy #Obj;
END TRY
BEGIN CATCH
EXEC sp_OADestroy #Obj;
END CATCH
SET NOCOUNT OFF
END
This is the query I execute:
exec dbo.ExportImage '2042','C:\ExpImg','2042.jpg'
Errormsg:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <=, >, >= or when the subquery is used as an expression.
Something like that:
CREATE PROCEDURE dbo.ExportImage (
#ImgName NVARCHAR (100)
,#ImageFolderPath NVARCHAR(1000)
,#Filename NVARCHAR(1000)
)
AS
BEGIN
DECLARE #ImageData VARBINARY (max);
DECLARE #Path2OutFile NVARCHAR (2000);
DECLARE #Obj INT
SET NOCOUNT ON
DECLARE #cursor CURSOR
SET #cursor = CURSOR FOR
SELECT convert (VARBINARY (max), ImgData, 1)
FROM Images
WHERE TicketID = #ImgName
OPEN #cursor
FETCH NEXT
FROM #cursor INTO #ImageData
WHILE ##FETCH_STATUS = 0
BEGIN
SET #Path2OutFile = CONCAT (
#ImageFolderPath
,'\'
, #Filename
);
BEGIN TRY
EXEC sp_OACreate 'ADODB.Stream' ,#Obj OUTPUT;
EXEC sp_OASetProperty #Obj ,'Type',1;
EXEC sp_OAMethod #Obj,'Open';
EXEC sp_OAMethod #Obj,'Write', NULL, #ImageData;
EXEC sp_OAMethod #Obj,'SaveToFile', NULL, #Path2OutFile, 2;
EXEC sp_OAMethod #Obj,'Close';
EXEC sp_OADestroy #Obj;
END TRY
BEGIN CATCH
EXEC sp_OADestroy #Obj;
END CATCH
FETCH NEXT
FROM #cursor INTO #ImageData
END
CLOSE #cursor
DEALLOCATE #cursor
END

SQL Pass Parameters from One stored proc to another

I have two SQL scripts: Script A and B. Script A retrieves information and uses the sp_executesql command to call stored procedure (Script B). I can successfully accomplish this.
However, now i would like to pass a value from Script A to Script B. I am unable to accomplish this. #nID is the parameter I would like to pass. I am using this link as a reference https://msdn.microsoft.com/en-IN/library/ms188001.aspx
My scripts are attached. For simplicity, I just made my parameter value equal to 5. So how do I pass a '5' from one script to another? Thanks for any help.
Script A
BEGIN
SET NOCOUNT ON;
DECLARE #sp nVARCHAR(25)
DECLARE #nID nvarchar(25)
DECLARE #busID nvarchar(25)
DECLARE #ParmDefinition nvarchar(500)
SET #ParmDefinition = N'#nID nvarchar(50) output ';
set #sp = 'WMCOMM';
set #busID = 5
execute sp_executesql #sp, #ParmDefinition, #nID = #busID;
END
Script B
ALTER PROCEDURE [dbo].[WMCM]
AS
BEGIN
SET nocount ON;
declare #numID nvarchar(50)
insert into tester(numid)
values(#numID)
END
Stored procedure B requires an input parameter
ALTER PROCEDURE [dbo].[WMCM]
#nID nvarchar(25) --DECLARE PARAMETER HERE THEN YOU CAN USE IT IN THE SP
AS
BEGIN
SET nocount ON;
declare #numID nvarchar(50)
insert into tester(numid)
values(#numID)
END
Here's a working template of what you are trying to acheive.
--RUN ME FIRST
CREATE procedure dbo.B
#nID AS NVARCHAR(5)
AS
SELECT #nID
GO
--RUN ME SECOND
CREATE procedure dbo.A
AS
DECLARE #nID NVARCHAR(50) = 'abc'
DECLARE #sp NVARCHAR(50) = 'EXECUTE dbo.B #nID'
EXECUTE sp_executesql #sp,N'#nID NVARCHAR(50)',#nID = #nID;
GO
--RUN ME THIRD
EXEC dbo.a
I dumbed-down the stored procedure to only show and return.
But this does what you want:
alter PROCEDURE [dbo].[WMCM]
#nID nvarchar(25) --DECLARE PARAMETER HERE THEN YOU CAN USE IT IN THE SP
, #InAndOutValue nvarchar(50) OUTPUT
AS
BEGIN
SET nocount ON;
Select '[dbo].[WMCM] has access to :' as ProcName , #nID as TheId
Select '[dbo].[WMCM] can use same variable as input and output. InValue :' as ProcName , #InAndOutValue as TheId
select #InAndOutValue= 'NowImAnOutValue'
END
GO
DECLARE #SQL_String NVARCHAR(max)
DECLARE #Parameter_Definition NVARCHAR(max)
SET #SQL_String = N'
EXEC [dbo].[WMCM] #nID = #nID_input, #InAndOutValue = #InAndOutValue_out OUTPUT
'
SET #Parameter_Definition = N'
#nID_input nvarchar(25),
#InAndOutValue_out nvarchar(50) OUTPUT'
DECLARE #nID nvarchar(25)
DECLARE #InAndOutValue nvarchar(50)
SET #nID = '5'
SET #InAndOutValue = 'InAndOutVariable_JustInValue'
EXECUTE sp_executesql #SQL_String, #Parameter_Definition, #nID_input = #nID, #InAndOutValue_out = #InAndOutValue OUTPUT
SELECT #InAndOutValue as IGotTheInAndOutValue

i want to pass a select query in a stored procedure as an argumnet

I made this procedure..
ALTER PROCEDURE [dbo].[MyProcedure]
#pSelect nvarchar
AS
BEGIN
SET NOCOUNT ON;
select #pSelect from tabel1
END
I want to pass a select query like from c# code to this stored procedure
MyProcedure("column1,column2");
How could I do this because stored procedure treat my parameter as a string and it behaves like
select N'column1,column2' from tabel1
pls help me
or provide a better option for this
You'll have to use dynamic sql inside the stored procedure.
ALTER PROCEDURE [dbo].[MyProcedure]
#pSelect nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL nvarchar(max)
SET #SQL = 'select ' + #pSelect + ' from tabel1';
EXEC (#SQL)
END
Here's a script to test the above stored procedure:
CREATE TABLE tabel1 (id int, data varchar(50))
INSERT INTO tabel1 VALUES(1,'aaa'),(2,'bbb'),(3,'ccc')
EXEC [dbo].[MyProcedure] 'id'
EXEC [dbo].[MyProcedure] 'data'
EXEC [dbo].[MyProcedure] 'id,data'
You can use dynamic SQL for the purpose, but it is not recommended. (More info here - The Curse and Blessings of Dynamic SQL)
create procedure MyProcedure
#pSelect nvarchar
AS
begin
declare #sql nvarchar(4000);
set #sql='select ['+ #pSelect +'] from Table_1';
exec sp_executesql #sql
end
go
exec MyProcedure 'column1,column2'
go
If your #pSelect is having entire query then:
ALTER PROCEDURE [dbo].[MyProcedure]
#pSelect nvarchar
AS
BEGIN
SET NOCOUNT ON;
-- If you are#pSelect is having entire query
exec (#pSelect)
-- If you are passing only field list then following
DECLARE #SQL nvarchar(max)
SET #SQL = 'select ' + #pSelect + ' from tabel1';
END

How to attach a file to an email using SQL stored procedure?

Can't seem to find much information about how to attach a file that's been stored as a BLOB as part of an email.
I know you can attach files from the file system (C:\temp...) to email that are being setup in DBMAIL or custom stored procedures. However, I haven't seen any references to attaching something such as a PDF that's been stored as a binary object in a table.
I see where you can attach a query as a file, but I don't think that's what I'm looking for.
We would do this programatically via the application, but we need to be able to kick this SP via triggers or the application's server side code.
Is this possible or should i be asking other questions, since usually a binary object also needs to have a content type associated with it for browsers or mail objects to know how to handle?
The solution can not attach binary object stored in db field, you may change your schema a little bit store the path to the binary file. if you could enable .net clr in your database server, you will have more options.
use master
go
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_send_cdosysmail]')
and objectproperty(id, N'isprocedure') = 1)
drop procedure [dbo].[usp_send_cdosysmail]
go
create procedure usp_send_cdosysmail
#from varchar(500) ,
#to varchar(500) ,
#subject varchar(500),
#body nvarchar(max) ,
#smtpserver varchar(25),
#bodytype varchar(10) ,
#attachment varchar(100)= ' '
as
declare #imsg int
declare #hr int
declare #source varchar(255)
declare #description varchar(500)
declare #output varchar(1000)
exec #hr = sp_oacreate 'cdo.message', #imsg out
exec #hr = sp_oasetproperty #imsg,
'configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").value','2'
exec #hr = sp_oasetproperty #imsg, 'configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").value', #smtpserver
exec #hr = sp_oamethod #imsg, 'configuration.fields.update', null
exec #hr = sp_oasetproperty #imsg, 'to', #to
exec #hr = sp_oasetproperty #imsg, 'from', #from
exec #hr = sp_oasetproperty #imsg, 'subject', #subject
-- if you are using html e-mail, use 'htmlbody' instead of 'textbody'.
exec #hr = sp_oasetproperty #imsg, #bodytype, #body
-- Attachments...
IF #attachment IS NOT NULL AND LEN(#attachment) > 0 BEGIN
Declare #files table(fileid int identity(1,1),[file] varchar(255))
Declare #file varchar(255)
Declare #filecount int ; set #filecount=0
Declare #counter int ; set #counter = 1
DECLARE #outVar INT
SET #outVar = NULL
INSERT #files SELECT cValue FROM master..fn_split(#attachment,',')
SELECT #filecount=##ROWCOUNT
WHILE #counter<(#filecount+1)
BEGIN
SELECT #file = [file]
FROM #files
WHERE fileid=#counter
EXEC #hr = sp_OAMethod #imsg, 'AddAttachment',#outVar OUT, #file
SET #counter=#counter+1
END
END
exec #hr = sp_oamethod #imsg, 'send', null
-- sample error handling.
if #hr <>0
select #hr
begin
exec #hr = sp_oageterrorinfo null, #source out, #description out
if #hr = 0
begin
select #output = ' source: ' + #source
print #output
select #output = ' description: ' + #description
print #output
end
else
begin
print ' sp_oageterrorinfo failed.'
return
end
end
exec #hr = sp_oadestroy #imsg
go
set quoted_identifier off
go
set ansi_nulls on
go
sp_configure 'Ole Automation Procedures', 1
RECONFIGURE
GO