Handle string or binary data would be truncated - sql

I have two procedure, one just return image in varbinary format and another one get that value and assign it in a variable. But I am getting:
String or binary data would be truncated.
Here I included both procedure below:
ALTER PROCEDURE [dbo].[Common_Sp_GetImage](#imagePath varchar(MAX), #Result VARBINARY(max) OUTPUT)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--EXEC master..xp_cmdshell 'net use Y: \\192.168.1.175\Rack /user:192.168.1.175\SPLITPC07 IT#2022';
-- Insert statements for procedure here
DECLARE #SQL varchar(max) =
N'SELECT #Result = BulkColumn
FROM OPENROWSET(BULK ''Y:' + #imagePath + N''', SINGLE_BLOB) AS t';
EXECUTE sp_executesql #SQL, N'#Result varbinary(max) OUTPUT', #Result OUTPUT;
RETURN #Result;
END
Another one is:
ALTER PROCEDURE [dbo].[Sales_Sp_MoneyRecipt]
-- Add the parameters for the stored procedure here
#CollectionId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Your insert TSQL here.
declare #CompanyImage varbinary(max)
declare #ProjectShornaliImage varbinary(max)
declare #ProjectSunvalleyImage varbinary(max)
EXEC GetImageProcedure '\Common\SwadeshLogo.jpg', #CompanyImage OUTPUT;
EXEC GetImageProcedure '\Common\ShornaliLogoEn.jpg', #ProjectShornaliImage OUTPUT;
EXEC GetImageProcedure '\Common\SunvalleyLogoEn.jpg', #ProjectSunvalleyImage OUTPUT;
select
'Money Receipt' ReportName,
dbo.GetCompanyName() as CompanyName,
dbo.GetCompanyAddress() as CompanyAddress,
ci.MRIdentity,
ci.MRNo,
ci.MRDate,
si.ApplicationId,
c.ClientName,
dbo.GetSalesMasterName(si.PlotType, 4) PlotType,
cti.CollectionTypeName CollectionType,
CONCAT(Left(ci.InstallmentFrom, 4), + '-' + DateName( month , DateAdd( month , CONVERT(int, RIGHT(ci.InstallmentFrom, 2)) , -1 ))) FromYearMonth,
CONCAT(Left(ci.InstallmentTo, 4), + '-' + DateName( month , DateAdd( month , CONVERT(int, RIGHT(ci.InstallmentTo, 2)) , -1 ))) ToYearMonth,
si.ProjectId,
Case when si.ProjectId = 1 then #ProjectShornaliImage else #ProjectSunvalleyImage end as ProjectImage,
dbo.GetProjectNameEnglish(si.ProjectId) ProjectName,
si.TotalArea,
dbo.GetMasterName(ci.MRType, 49) MRType,
ci.ChequeNo,
ci.ChequeDate,
b.BankName,
ci.Amount,
#CompanyImage as CompanyImage
from Sales_CollectionInfo ci
inner join Sales_CollectionTypeInfo cti on ci.CollectionType = cti.CollectionTypeId
inner join Sales_SaleInfo si on ci.SalesId = si.SaleId
inner join Sales_ClientInfo c on si.ClientId = c.ClientId
left join BankInfo b on ci.ChequeBank = b.Id
where ci.CollectionId = #CollectionId
END

Related

dynamic pivot with parameter passed in

I have created this stored procedure that works when hard coded
(in the where clause at #WeekStart and #WeekEnd),
If I try to add parameters to the query #WeekStart and #WeekEnd I get the following error:
Must declare the scalar variable "#WeekStart".
My goal is to do do something like this instead of having to hard code it:
exec dbo.GetTotals #WeekStart='2022-04-11',#WeekEnd='2022-04-25'
The stored procedure:
CREATE PROCEDURE [dbo].[GetTotals]
#WeekStart Date,
#WeekEnd Date
AS
begin
set nocount on;
--get row names
DECLARE
#columns NVARCHAR(MAX) = '',
#sql NVARCHAR(MAX) = '';
-- select the category names
SELECT
#columns+=QUOTENAME(DepartmentName) + ','
FROM
DepartmentTable
ORDER BY
DepartmentName;
--set#colums variable
SET #columns = LEFT(#columns, LEN(#columns) - 1);
-- construct dynamic SQL
SET #sql ='
SELECT * FROM
(
select
JobCode,
DepartmentName,
(COALESCE(MonTime, 0)+COALESCE(TueTime, 0)+COALESCE(WenTime, 0)+COALESCE(ThurTime, 0)+COALESCE(FriTime, 0)
+COALESCE(SatTime, 0)+COALESCE(SunTime, 0)) as total
from TimeSheetTable
INNER JOIN DepartmentTable ON TimeSheetTable.DeptId=DepartmentTable.Id
inner join JobCodeTable on TimeSheetTable.JobId=JobCodeTable.Id
--This Works--
-- Where WeekStartDate Between ''2022-04-11'' and ''2022-04-11'' --
--This is throwing an erro--
Where WeekStartDate Between #WeekStart and #WeekEnd
) t
PIVOT(
sum(total)
FOR DepartmentName IN ('+ #columns +')
)pivot_table
ORDER BY JobCode
'
---- execute the dynamic SQL
EXECUTE sp_executesql #sql;
end
exec sp_executesql #Sql, N' #WeekStart Date, #WeekEnd Date', #WeekStart = #WeekStart, #WeekEnd = #WeekEnd

Using cursor to loop through a table variable in SQL Server

I have a parameter of a stored procedure which gets some data in the format
1/1/2018-2/1/2018,2/1/2018-3/1/2018,3/1/2018-4/1/2018,4/1/2018-5/1/2018,5/1/2018-6/1/2018,6/1/2018-7/1/2018,7/1/2018-8/1/2018,8/1/2018-9/1/2018,9/1/2018-10/1/2018,
10/1/2018-11/1/2018,11/1/2018-12/1/2018,12/1/2018-12/31/2018
I have a function which splits the data based on the , character and stores the results into a table variable as shown here:
declare #SPlitDates table(ItemNumber int, Item nvarchar(max))
insert into #SPlitDates
select *
from dbo.SPlitFunction(#RequestData, ',')
After this I have to perform certain operations on the data range so I use cursors to loop through the temp table as shown below
DECLARE cur CURSOR FOR
SELECT Item
FROM #SPlitDates
ORDER BY ItemNumber
OPEN cur
FETCH NEXT FROM cur INTO #monthStart
WHILE ##FETCH_STATUS = 0
BEGIN
-- Some operation
END
The max data points that I will get in the temp table is the date range for 12 months.
My question is that could I be using something else apart from cursors to improve performance or it doesn't matter when the dataset is really this small.
Thanks
Edit - To show operation inside the cursor
declare #SPlitDates table(ItemNumber int, Item nvarchar(max))
insert into #SPlitDates
select *
from dbo.SPlitFunction(#RequestData, ',')
declare #SPlitDatesData table (ItemNumber varchar(100), Item nvarchar(max))
declare #SPlitDatesAvgData table(Code nvarchar(100), Val decimal(18,2))
declare #dataFilter as nvarchar(max),
#SQL as nvarchar(max);
declare #monthStart nvarchar(100)
declare #count int
set #count = 0
--Declaring a cursor to loop through all the dates as defined in the requested quarter
DECLARE cur CURSOR FOR
SELECT Item
FROM #SPlitDates
ORDER BY ItemNumber
OPEN cur
FETCH NEXT FROM cur INTO #monthStart
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #Period NVARCHAR(100)
SET #Period = #monthStart
INSERT INTO #SPlitDatesData
--split the dates to get the start and the end dates
SELECT *
FROM dbo.SPlitFunction(#Period, '-')
DECLARE #PeriodStart NVARCHAR(100)
DECLARE #PeriodEnd NVARCHAR(100)
SET #PeriodStart = (SELECT Item FROM #SPlitDatesData WHERE ItemNumber = 1)
SET #PeriodEnd = (SELECT Item FROM #SPlitDatesData WHERE ItemNumber = 2)
DELETE FROM #SPlitDatesData
--add the start and end dates to the filter
SET #dataFilter = 'StatusDate between convert(datetime,('''+#PeriodStart+'''))
and DATEADD(dy, 1, convert(datetime,('''+#PeriodEnd+''')))'
SET #count = #count +1;
SET #SQL = 'INSERT INTO #BidAverageCycleCalculation (SortOrder, Code, Data)
VALUES (#count,
''SL Payroll'',(select dbo.GetAverageCycleBetweenBids('''+#PeriodStart+''',
'''+#PeriodEnd+''',''SL''))
)'
EXEC SP_ExecuteSQL #SQL, N'#count int', #count;
SET #count = #count +1;
SET #SQL = 'INSERT INTO #BidAverageCycleCalculation (SortOrder, Code, Data)
VALUES (#count,
''GV Payroll'',(select dbo.GetAverageCycleBetweenBids('''+#PeriodStart+''',
'''+#PeriodEnd+''',''GV''))
)'
EXEC SP_ExecuteSQL #SQL , N'#count int', #count;
SET #count = #count +1;
SET #SQL = 'Insert into #BidAverageCycleCalculation (SortOrder,Code,Data)
Values (#count,
''Global Payroll'',(select dbo.GetAverageCycleBetweenBids('''+#PeriodStart+''',
'''+#PeriodEnd+''',''GVS''))
)'
EXEC SP_ExecuteSQL #SQL, N'#count int', #count;
SET #count = #count +1;
SET #SQL = 'Insert into #BidAverageCycleCalculation (SortOrder,Code,Data)
Values (#count,
''TimeHCM'',(select dbo.GetAverageCycleBetweenBids('''+#PeriodStart+''',
'''+#PeriodEnd+''',''Time''))
)'
EXEC SP_ExecuteSQL #SQL, N'#count int', #count;
delete from #SPlitDatesAVgData
FETCH NEXT FROM cur INTO #monthStart
END
CLOSE cur
DEALLOCATE cur
This uses two parts - first convert your string into a table, then do bulk inserts into your destination. No need for cursors.
** Please excuse any syntax errors as I'm doing it without access to your actual tables or functions so cant test it, but you get the idea
declare #in varchar(max)
set #in= '1/1/2018-2/1/2018,2/1/2018-3/1/2018,3/1/2018-4/1/2018,4/1/2018-5/1/2018,5/1/2018-6/1/2018,6/1/2018-7/1/2018,7/1/2018-8/1/2018,8/1/2018-9/1/2018,9/1/2018-10/1/2018,10/1/2018-11/1/2018,11/1/2018-12/1/2018,12/1/2018-12/31/2018'
declare #xml xml;
set #xml= convert(xml,'<r><f>'+replace(replace(#in,',','</t></r><r><f>'),'-','</f><t>') +'</t></r>')
declare #t table(id int identity, f date, t date)
insert #t
select
Tbl.Col.value('f[1]', 'date') f,
Tbl.Col.value('t[1]', 'date') t
FROM #xml.nodes('//r') Tbl(Col)
select * from #t
declare #count int;
select #count=count(*) from #t
INSERT INTO #BidAverageCycleCalculation (SortOrder, Code, Data)
select id, 'SL Payroll',(select dbo.GetAverageCycleBetweenBids(f,t,'SL')) from #t
INSERT INTO #BidAverageCycleCalculation (SortOrder, Code, Data)
select id+#count,'GV Payroll',(select dbo.GetAverageCycleBetweenBids(f,t,'GV')) from #t
INSERT INTO #BidAverageCycleCalculation (SortOrder, Code, Data)
select id+#count*2,'Global Payroll',(select dbo.GetAverageCycleBetweenBids(f,t,'GVS')) from #t
INSERT INTO #BidAverageCycleCalculation (SortOrder, Code, Data)
select id+#count*3,'TimeHCM',(select dbo.GetAverageCycleBetweenBids(f,t,'Time')) from #t

Renaming table and view from a different database, works in editor but not from stored procedure

I have to run a monthly job in SQL Server to rename a table and a view in a variety of databases. The database names are stored in a table and this procedure loops through them. The table names change monthly, so I am concatenating the table names based on the current date.
This works well to creating the commands.
If I change my EXEC to PRINT and paste the results into a new query window it works great.
BW_Test.dbo.sp_rename 'BW_Test_DataLog_2018_05','BW_Test_DataLog_2018_06';
BW_Test.dbo.sp_rename 'BW_Test_DataLog','BW_Test_DataLog_2018_05';
However when I run the stored procedure it fails with the following error:
ErrorNumber: 2812 ErrorMessage: Could not find stored procedure 'BW_Test.dbo.sp_rename 'BW_Test_DataLog_2018_05','BW_Test_DataLog_2018_06';'
Here is the stored procedure, thanks in advance!
BEGIN
SET NOCOUNT ON;
-- Find month and year to concatenate with table names
DECLARE #RighNow DATE = GETDATE();
DECLARE #LastMonth DATE = DATEADD(MONTH, -1, GETDATE());
DECLARE #RenameView NVARCHAR(500);
DECLARE #RenameTable NVARCHAR(500);
DECLARE #LastMonthsName NVARCHAR(50);
DECLARE #ThisMonthsName NVARCHAR(50);
DECLARE #COUNTER INT = 0;
DECLARE #MAX INT = (SELECT COUNT(*) FROM DatabaseNames)
DECLARE #Machine VARCHAR(50);
--Start Loop here
WHILE #COUNTER < #MAX
BEGIN
SET #Machine = (SELECT DatabaseName
FROM
(SELECT
(ROW_NUMBER() OVER (ORDER BY (SELECT NULL))) [index],
DatabaseName
FROM
DatabaseNames) R
ORDER BY R.[index]
OFFSET #COUNTER ROWS FETCH NEXT 1 ROWS ONLY);
SET #LastMonthsName = CONCAT(#Machine, '_DataLog', '_', YEAR(#LastMonth), '_', FORMAT(MONTH(#LastMonth), '00'));
SET #ThisMonthsName = CONCAT(#Machine, '_DataLog', '_', YEAR(#RighNow), '_', FORMAT(MONTH(#RighNow), '00'));
SET #RenameView = CONCAT(#Machine, '.dbo.sp_rename ', char(39), #LastMonthsName, char(39), ',', char(39), #ThisMonthsName, char(39), ';');
SET #RenameTable = CONCAT(#Machine, '.dbo.sp_rename ', char(39), #Machine, '_DataLog', char(39), ',', char(39), #LastMonthsName, char(39), ';');
BEGIN TRY
--IMPORTANT - Change the View first or you will have duplicate table names
EXEC #RenameView
EXEC #RenameTable
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
SET #COUNTER = #COUNTER + 1
END
END
Change
EXEC #RenameView
EXEC #RenameTable
to:
EXEC (#RenameView)
EXEC (#RenameTable)
The problem is that EXEC has actually 2 different implementations, one for dynamic SQL (with parenthesis) and another for procedures (without).

SQL Job to Pipe Delimited

I am running SQL Job (SQL Server 20208 R2) and I want the results of the script to save to a folder as pipe delimited. Is there any way of doing that by adding to the script? Below is the script. If not can I do it any other way?
SELECT Distinct
(SELECT REPLACE(CONVERT(VARCHAR(10),PatientDemographics.DateofBirth,101),'/','')) as DOB
, (SELECT REPLACE(CONVERT(VARCHAR(10),ScheduleEntry.ScheduleDate,101),'/','')) as DateofService
, RTRIM(LTRIM(Insurances.EligibilityPayorNumber)) as InsurancePayorCode
, RTRIM(LTRIM(ContractFacilityProviders.NPI)) as ProviderID
, RTRIM(LTRIM(PatientInsuranceProfiles.Insurance1PolicyNumber)) as SubscriberInsuranceID
, RTRIM(LTRIM(PatientInsuranceProfiles.Insurance1PolicyGroupNumber)) as SubscriberGroupNumber
, RTRIM(LTRIM(PatientDemographics.firstname)) as SubscriberFirstName
, RTRIM(LTRIM(PatientDemographics.MiddleInitial)) as SubscriberMiddleInitial
, RTRIM(LTRIM(PatientDemographics.Lastname)) as SubscriberLastName
FROM
ScheduleEntry
LEFT JOIN
PatientDemographics ON ScheduleEntry.PatientAccount = PatientDemographics.AccountNumber
LEFT JOIN
Providers ON ScheduleEntry.ResourceCode = Providers.MedStarProviderIdentifier
LEFT JOIN
Facilities ON ScheduleEntry.FacilityCode = Facilities.MedStarFacilityIdentifier
LEFT JOIN
AddedResource ON ScheduleEntry.ResourceCode = AddedResource.AddedResourceCode
LEFT JOIN
Caregiver ON ScheduleEntry.ResourceCode = Caregiver.CaregiverCode
LEFT JOIN
PatientInsuranceProfiles ON ScheduleEntry.PatientAccount = PatientInsuranceProfiles.PatientAccountNumber
LEFT JOIN
Insurances ON PatientInsuranceProfiles.Insurance1Mnemonic = Insurances.Mnemonic
LEFT JOIN
ContractFacilityProviders ON PatientDemographics.PrimaryPhysician = ContractFacilityProviders.ProviderIdentifier
WHERE
ScheduleEntry.ScheduleDate >= getdate()
AND ScheduleEntry.ScheduleDate <= getDate() + .50
AND PatientInsuranceProfiles.Insurance1ContractIdentifier = ContractFacilityProviders.ContractIdentifier
AND PatientinsuranceProfiles.ActiveFlag = 1
AND EligibilityPayorNumber > 1
AND ContractFacilityProviders.NPI > 1
ORDER BY
SubscriberLastName
You can xp_cmdshell with something like....
SELECT DISTINCT
--your columns
INTO ##PIPE_FILE
FROM YourTables
INNER JOIN YourOtherTables
EXECUTE master.dbo.xp_cmdshell
'bcp "SELECT * FROM ##PIPE_FILE " queryout C:\Folder\Pipes.txt -t"|" -c -T '
Several ideas
1) Write an SSIS package to export to a flat file, using the pipe as the delimiter.
2) Use BCP as stated already
3) Use sqlcmd to output the result
SSIS will be a nice solution for a SQL job.
I would also echo the previous posters who suggested checking that your aren't negating the effects of your left joins by using the tables in the where clause
EDIT: If you don't have access to xp_cmdshell (many DBAs turn this
off)
The following will take the results of #TempPipe and dynamically save it as a pipe delimited (with a header -- optional) to your desired location.
Now, you will need the stored procedure listed below, along with the appropriate writes.
-- Assumes your query will be saved to #TempPipe
Select * Into #TempPipe from OD
-- Set Destination File
Declare #Destination varchar(250) = 'C:\Working\Test_Pipe.txt'
-- Construct Field Name and Header from #TempPipe
Declare #Header varchar(max) = '>>>'
Select #Header = #Header +']|['+Name from (select * from tempdb.sys.columns where object_id = object_id('tempdb..#TempPipe') ) A Order by column_id
Select #Header = Replace(#Header,'>>>]|','')+']'
Declare #SelectHead varchar(max) = 'Select Pipe=cast(Replace(Replace('''+#Header+''',''['',''''),'']'','''') as varchar(max)) '
Declare #SelectData varchar(max) = 'Select Pipe=cast(concat('+Replace(#Header,'|',',''|'',')+') as varchar(max)) from #TempPipe '
--If Version<2012 Declare #SelectData varchar(max) = 'Select Pipe=cast(cast('+Replace(#Header,'|',' as varchar(500))+''|''+cast(')+' as varchar(500)) as varchar(max)) from #TempPipe '
Declare #SQL varchar(max) ='
Declare #String varchar(max) = '''';
Select #String = #String + Pipe + char(13)+char(10) From ('+#SelectHead+' Union All '+#SelectData+' ) A
Exec [dbo].[prc-Write-To-File] #String, ''' + #Destination +'''
'
--Select #SQL
Exec(#SQL)
The stored procedure to write any string to any file
EXEC sp_configure 'show advanced options', 1
GO
EXEC sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
CREATE Procedure [dbo].[prc-Write-To-File] (#text as Varchar(Max), #Filename Varchar(200)) AS
Begin
Declare #Object int,#rc int,#FileID Int
EXEC #rc = sp_OACreate 'Scripting.FileSystemObject', #Object OUT
EXEC #rc = sp_OAMethod #Object , 'OpenTextFile' , #FileID OUT , #Filename , 2 , 1
Set #text = Replace(Replace(Replace(#text,'&','&'),'<' ,'<'),'>','>')
EXEC #rc = sp_OAMethod #FileID , 'WriteLine' , Null , #text
Exec #rc = [YourDatabaseName].dbo.sp_OADestroy #FileID
Declare #Append bit
Select #Append = 0
If #rc <> 0
Begin
Exec #rc = [YourDatabaseName].dbo.sp_OAMethod #Object, 'SaveFile',null,#text ,#Filename,#Append
End
Exec #rc = [YourDatabaseName].dbo.sp_OADestroy #Object
End
Small sample of the text file generated
ODNr|ODID|ODClass|ODTitle|ODLMUsr|ODLMUTC|ODDeleted
0|UNDEF|UNDEF|Undefined|2|Apr 5 2016 1:40PM|0
1|SYSTEM|UNDEF|System|2|Apr 5 2016 1:40PM|0
2|UNDEF|USER|Cappelletti, John|2|Apr 12 2016 7:04PM|0
3|UNDEF|UNDEF|Daily Production Summary|2|Apr 14 2016 12:28PM|0

Sum up values from databases and parametrize it. [SQL Server]

I want to sum up values from several databases. At this moment I have three databases: SPA_PROD, SPB_PROD and SPC_PROD.
My SQL query:
IF EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[TESTSUM]')
AND TYPE IN (N'P',N'PC'))
DROP PROCEDURE [dbo].[TESTSUM]
GO
CREATE PROC TESTSUM
AS
BEGIN
DECLARE #dbName SYSNAME,
#ObjectSUM INT,
#d datetime
SET #d = '20141113'
DECLARE #SQL NVARCHAR(MAX)
DECLARE #DBObjectStats TABLE (
--DBName SYSNAME,
DBObjects INT)
DECLARE curAllDBs CURSOR FOR
SELECT name
FROM MASTER.dbo.sysdatabases
WHERE name like '%PROD'
ORDER BY name
OPEN curAllDBs
FETCH curAllDBs INTO #dbName
WHILE (##FETCH_STATUS = 0) -- db loop
BEGIN
--SQL QUERY
SET #SQL = 'select #dbObjects = sum(doctotal) from ' +
QuoteName(#dbName) + '..Invoice
where DocDate = ''' + cast(#d as varchar(25)) + ''''
PRINT #SQL -- Debugging
EXEC sp_executesql #SQL, N'#dbObjects int output',
#dbObjects = #ObjectSUM output
INSERT #DBObjectStats
SELECT #ObjecSUM
FETCH curAllDBs INTO #dbName
END
CLOSE curAllDBs
DEALLOCATE curAllDBs
-- Return results
SELECT sum(DBObjects) [InvoiceSUM] FROM #DBObjectStats
END
GO
-- Execute stored procedure
EXEC TESTSUM
GO
And this work perfect and giving me right sum from all my DBs: 120 000$ ( 25 000 from SPA_PROD , 95 000 SPC_PROD and 0 (NULL) from SPB_PROD.
What I want to do:
I would like to parametrize, which allows me to choose date and databases. For example I want to choose SPA_PROD and SPB_PROD with date 2014-01-01 in another case I want all databases (SPA + SPB + SPC with another date.
Is this even possible? Any ideas?
I can use everything what gives me SQL Server 2012 and T-SQL. Maybe this technology offers me easiest way to do this.
I am also using SAP Crystal Reports to convert SQL output into a beautiful report.
Sorry for my English and I tried to describe to you my problem as far as I could. If you want any additional information which helps u to help me -> ask me :).
You can create a User-Defined Table Type:
CREATE TYPE DBTable AS TABLE
(
DBName VARCHAR(128)
);
You can use it as an input parameter of your stored procedure. As well as the date parameter.
CREATE PROCEDURE TESTSUM
#Databases DBTable READONLY
,#Date DATETIME
AS
BEGIN
...
...
...
You call it like this:
DECLARE #T AS DBTable;
DECLARE #D AS DATETIME = GETDATE();
INSERT INTO #T VALUES ('DB1', 'DB2', 'DB3')
EXEC TESTSUM #T, #D
maybe instead of
SELECT name
FROM MASTER.dbo.sysdatabases
use
SELECT name
FROM #temptable
and insert into #temptable specific db you want
Using your example I modified it to accept a string of database names (generated through you crystal reports select action). Then passing this string with the date in question to first validate the database exist and if online add the required union clause to the generated SQL code.
CREATE PROCEDURE TESTSUM
#DbNameS NVARCHAR(max)
,#Date DATETIME
AS
BEGIN
DECLARE #SQL NVARCHAR(MAX) = ''
/* ADD EXTRA ',' RO STRING ARRAY OF DATABASES */
SET #DbNameS = #DbNameS + ',';
DECLARE #L INT = LEN(#DbNameS);
DECLARE #D INT = 0;
DECLARE #LD INT = 1;
DECLARE #DBF VARCHAR(50);
DECLARE #ACTIVE INT = 0;
/* START SQL QUERY */
SET #SQL = 'SELECT SUM([InvoiceSUM]) AS [InvoiceSUM] FROM ( SELECT '''' AS DB, 0.00 AS [InvoiceSUM]' + CHAR(13)
/* LOOP THROUGH EACH DBF NAME PASSED CHECKING IF VALID AND ONLINE */
WHILE #D < #L
BEGIN
SET #D = CHARINDEX(',', #DbNameS,#LD);
IF #LD != #D
BEGIN
SET #DBF = SUBSTRING(#DbNameS,#LD,#D-#LD)
/* VALIDATE DBF IS VALID AND ACTIVE */
SELECT #ACTIVE = COUNT(*) FROM SYS.databases WHERE name = #DBF AND [state] = 0
IF #ACTIVE = 1
BEGIN
/*
BEGIN CODE TO UNION THE SUM RESULTS FOR EACH ACTIVE AND VALID DBF
TO MAKE IT WORK WITH SOME EXISTING DBF's ON MY SYSTEM I CHANGED THE SUMMARY CODE FOR TESTING
*/
SET #SQL = #SQL + 'UNION SELECT '''+ #DBF +''' AS DB, ISNULL(SUM( CAST(DVE AS DECIMAL(18,10)) ),0) AS [InvoiceSUM] FROM '+ #DBF + '.DBO.SO_MSTR WHERE CAST(RecordCreated AS DATE) = '''+ CAST(#Date AS VARCHAR(20)) + '''' + CHAR(13)
END;
END;
SET #LD = #D + 1;
END;
/* CLOSE OUT UNION SUMMARY QUERY */
SET #SQL = #SQL + ') AS DATA'
/* OUTPUT RESULTS */
EXEC SP_EXECUTESQL #SQL
END;
Crystal reports would effective be generating this code: EXEC TESTSUM 'SPA_PROD,SPB_PROD,SPC_PROD','12/09/2014'