I'm trying to write a procedure that executes another procedure within it, but I'm getting this error
Incorrect syntax near '#PRIMARY_AM'
but I get this error only with the variables that have a CAST() OR ISNULL() OR REPLACE() function. If I comment out the line with #PRIMARY_AM it will then say
Incorrect syntax near 'ISNULL'
CREATE PROCEDURE [dbo].[RUN_PROCESS]
#PRIMARY_NO VARCHAR(20) = NULL,
#COMBINED_AM INT = NULL,
#PRIMARY_BOR VARCHAR(40) = NULL,
#PRIMARY_AM INT = NULL,
#SECONDARY_AM INT = NULL,
#SECONDARY_DT SMALLDATETIME = NULL,
#PRIMARY_CD VARCHAR(10) = NULL,
#O_ID INT OUTPUT
AS
EXEC dbo.LINK_PROCESS
#PRIMARY_NO = #PRIMARY_NO,
#COMBINED_AM = CAST(#PRIMARY_AM + #SECONDARY_AM AS VARCHAR),
#PRIMARY_BOR = REPLACE(ISNULL(#PRIMARY_BOR, ''), '''',' '),
#PRIMARY_AM = CAST(ISNULL(#PRIMARY_AM, 0) AS VARCHAR),
#SECONDARY_AM = CAST(ISNULL(#SECONDARY_AM, 0) AS VARCHAR),
#SECONDARY_DT = CAST(#SECONDARY_DT AS VARCHAR),
#PRIMARY_CD = ISNULL(#PRIMARY_CD, ''),
#O_ID = #O_ID OUTPUT;
If I remove those functions CAST(), REPLACE() and ISNULL() then I can execute the query without a problem. I don't know why this isn't working.
I'm using SQL Server 2005
This is the solution to my problem, thanks to Alex and his comment under my question
Stored procedures, accept parameters (variables and constants) but not
expressions. You need to do all casting before calling your SP. – Alex
CREATE PROCEDURE [dbo].[RUN_PROCESS]
#PRIMARY_NO VARCHAR(20) = NULL,
#COMBINED_AM INT = NULL,
#PRIMARY_BOR VARCHAR(40) = NULL,
#PRIMARY_AM INT = NULL,
#SECONDARY_AM INT = NULL,
#SECONDARY_DT SMALLDATETIME = NULL,
#PRIMARY_CD VARCHAR(10) = NULL,
#O_ID INT OUTPUT
AS
DECLARE #COMBINED VARCHAR
SET #COMBINED = CAST(#PRIMARY_AM + #SECONDARY_AM AS VARCHAR)
DECLARE #PRIM_BOR VARCHAR(40)
SET #PRIM_BOR = REPLACE(ISNULL(#PRIMARY_BOR, ''), '''',' ')
DECLARE #PRIM_AM VARCHAR
SET #PRIM_AM = CAST(ISNULL(#PRIMARY_AM, 0) AS VARCHAR)
DECLARE #SEC_AM VARCHAR
SET #SEC_AM = CAST(ISNULL(#SECONDARY_AM, 0) AS VARCHAR)
DECLARE #SEC_DT VARCHAR
SET #SEC_DT = CAST(#SECONDARY_DT AS VARCHAR)
DECLARE #PRIM_CD VARCHAR(10)
SET #PRIM_CD = ISNULL(#PRIMARY_CD, '')
EXEC dbo.LINK_PROCESS
#PRIMARY_NO = #PRIMARY_NO,
#COMBINED_AM = #COMBINED,
#PRIMARY_BOR = #PRIM_BOR,
#PRIMARY_AM = #PRIM_AM,
#SECONDARY_AM = #SEC_AM,
#SECONDARY_DT = #SEC_DT,
#PRIMARY_CD = #PRIM_CD,
#O_ID = #O_ID OUTPUT;
Related
I have the following table:
CREATE TABLE NZQA_Unit(
NZQAUnitID int IDENTITY(1,1) PRIMARY KEY NOT NULL,
NZQAUnitNumber int NOT NULL,
Title nvarchar(255) NOT NULL,
Level smallint NOT NULL,
Credits smallint NOT NULL,
Classification nvarchar(255) NULL,
AvailableGrade int NULL DEFAULT 1,
Purpose nvarchar(max) NULL,
Validity int NOT NULL DEFAULT 1, -- by default the unit will be 'Current'
Document VARBINARY(MAX) NULL, -- for being able to upload a PDF or Word document
DocumentExtension varchar(5) NULL, -- for storing the file extension
CONSTRAINT AK_NZQA_Unit_Title UNIQUE(Title),
CONSTRAINT AK_NZQA_Unit_Number UNIQUE(NZQAUnitNumber),
CONSTRAINT FK_NZQA_Unit_Validity FOREIGN KEY (Validity) REFERENCES NZQA_Unit_Validity (ValidityID),
CONSTRAINT FK_NZQA_Unit_AvailableGrade FOREIGN KEY (AvailableGrade) REFERENCES NZQA_Unit_Assessment_Grade (AssessmentGradeID),
CONSTRAINT CK_NZQA_Unit_Title CHECK ((len(ltrim(rtrim(Title)))>(2))),
CONSTRAINT CK_NZQA_Unit_ID_Range CHECK (NZQAUnitNumber >= 1000 AND NZQAUnitNumber <= 99999), --Inclusive
CONSTRAINT CK_NZQA_Unit_Level CHECK (Level >= 1 AND Level <= 10), -- Level must be between 1 and 10 https://www.nzqa.govt.nz/studying-in-new-zealand/understand-nz-quals/
CONSTRAINT CK_NZQA_Unit_Credits CHECK (Credits >= 1 AND Credits <= 999), -- 999 has been set arbitrarily but it's high enough to fit an Engineering Degree
CONSTRAINT CK_NZQA_Unit_DocumentSize CHECK (DATALENGTH(Document) <= 524288), -- Maximum size 500 KB https://stackoverflow.com/questions/34741079/can-i-set-2-mb-for-maximum-size-of-varbinary https://www.gbmb.org/mb-to-bytes
CONSTRAINT CK_NZQA_Unit_DocumentExtension CHECK (DocumentExtension IN ('.pdf', '.doc', '.docx')) -- this check is not case sensitive, i.e. '.DOCX' won't trigger an error
);
GO
And I'm writing the following stored procedure:
DROP PROCEDURE IF EXISTS Modify_NZQA_Unit
GO
CREATE PROCEDURE Modify_NZQA_Unit
#NZQAUnitID int,
#NZQAUnitNumber int,
#Title nvarchar(255),
#Level smallint,
#Credits smallint,
#Classification nvarchar(255) NULL,
#AvailableGrade int,
#Purpose nvarchar(max),
#Validity int,
#Document VARBINARY(MAX),
#DocumentExtension varchar(5),
#overwriteFile bit -- 1 to overwrite, 0 to no overwrite
AS
BEGIN
IF (#NZQAUnitID IS NULL)
BEGIN
THROW 51006, 'You must input the NZQA identifier (NZQAUnitID)', 1;
END
SET #Title = Replace(#Title, '''', '''''') -- singles quotes must be escaped
SET #Classification = Replace(#Classification, '''', '''''')
SET #Purpose = Replace(#Purpose, '''', '''''')
SET #DocumentExtension = Replace(#DocumentExtension, '''', '''''')
DECLARE #updateStatement AS NVARCHAR(1000);
SET #updateStatement = 'UPDATE NZQA_Unit SET NZQAUnitNumber = '+CONVERT(VARCHAR, #NZQAUnitNumber)+', Title = '''+#Title+''', Level = '+CONVERT(VARCHAR, #Level)+', Credits = '+CONVERT(VARCHAR, #Credits)+', Classification = '''+#Classification+''', AvailableGrade = '+CONVERT(VARCHAR, #AvailableGrade)+', Purpose = '''+#Purpose+''', Validity = '+CONVERT(VARCHAR, #Validity)
IF (#overwriteFile IS NULL)
BEGIN
THROW 51007, 'Variable #overwriteFile cannot be null', 1;
END
ELSE
BEGIN
IF (#overwriteFile = 1)
BEGIN
IF (#Document IS NULL)
BEGIN
THROW 51008, 'If the variable #overwriteFile is set to 1, a file (#Document) must be provided', 1;
END
IF (#DocumentExtension IS NULL)
BEGIN
THROW 51009, 'If the variable #overwriteFile is set to 1, the document extension (#DocumentExtension) must be provided', 1;
END
SET #updateStatement = #updateStatement + ', Document = '+'HERE WILL COME THE VARBINARY'+', DocumentExtension = '''+#DocumentExtension + ''' '
--DOESN'T WORK: EXEC('UPDATE NZQA_Unit SET NZQAUnitNumber = '+#NZQAUnitNumber+', Title = '''+#Title+''', Level = '+#Level+', Credits = '+#Credits+', Classification = '''+#Classification+''', AvailableGrade = '+#AvailableGrade+', Purpose = '''+#Purpose+''', Validity = '+#Validity + ', Document = ' + #document + ', DocumentExtension = '''+#DocumentExtension + ''' ' +' WHERE NZQAUnitID = '+#NZQAUnitID)
UPDATE NZQA_Unit SET NZQAUnitNumber = #NZQAUnitNumber, Title = #Title, Level = #Level, Credits = #Credits, Classification = #Classification, AvailableGrade = #AvailableGrade, Purpose = #Purpose, Validity = #Validity, Document = #document, DocumentExtension = #DocumentExtension WHERE NZQAUnitID = #NZQAUnitID
END
ELSE
BEGIN
UPDATE NZQA_Unit SET NZQAUnitNumber = #NZQAUnitNumber, Title = #Title, Level = #Level, Credits = #Credits, Classification = #Classification, AvailableGrade = #AvailableGrade, Purpose = #Purpose, Validity = #Validity WHERE NZQAUnitID = #NZQAUnitID
END
END
SET #updateStatement = #updateStatement +' WHERE NZQAUnitID = '+CONVERT(VARCHAR, #NZQAUnitID)
PRINT #updateStatement
END
GO
How could I insert the varbinary data (#Document) into the #updateStatement variable? That way I could simply do a EXEC(#updateStatement)?
Code to execute the procedure below:
DECLARE #current AS INT = 1
DECLARE #expiring AS INT = 2
DECLARE #expired AS INT = 3
DECLARE #achieved AS INT = 1
DECLARE #datos AS VARBINARY(30) = CONVERT(varbinary(30), N'this IS a test')
INSERT NZQA_Unit (NZQAUnitNumber, [Title], [Level], [Credits], [Classification], [AvailableGrade], [Purpose], Validity) VALUES (6401, N'Provide first aid', 2, 1, N'Health Studies > First Aid', #achieved, N'People credited with this unit standard are able to provide first aid.', #current)
EXEC Modify_NZQA_Unit 1, 6424, N'Provide first aid', 2, 1, N'Health Studies > First Aid', #achieved, N'People credited with this unit standard are able to provide first aid.', #current, #datos, '.pdf', 1
I am calling a stored procedure with optional params with an output parameter like below. I have tried ctx.Database.SqlQuery<string> and ExecuteSqlCommand. Both throws an error.
The stored procedure has these params with most of them being optional:
#Debug CHAR(1) = 'N',
#Yr VARCHAR(4),
#Collection_ID INT = NULL,
#SortOrder VARCHAR(100) = ' ',
#SrchDates VARCHAR(100) = '',
#FixedFormat CHAR(1) = 'C',
#ExtrctStrtFg CHAR(1) = 'D',
#APP_ID INT = NULL,
#MatchFound CHAR(1) = 'N' OUTPUT
My call is:
var retVal = frlentities.Database.SqlQuery<string>("exec pr_storedproc #Yr = 2000,#ExtrctStrtFg='F', #APP_ID=1234, #MatchFound OUTPUT;");
This complains that the fourth parameter #sortorder is provided as an output parameter. The same works when I do not have an output parameter and the I am getting a list with other stored procedures. Hope there is some way around this. I can provide all parameter by importing the stored procedure. But some stored procedures have too many parameters. Thank you
I wrote a stored procedure that filters my table. It is working fine, and selects the correct records, but in the result for example if query have to return one record.
Instead of one record return too many record is it possible my stored procedure executes several times?
I use this code:
ALTER PROCEDURE [dbo].[propertyFilterByCity]
#city NVARCHAR(150) = NULL,
#DefaultPageIndex smallint = NULL,
#DefaultPageSize smallint = NULL,
#RecordCount bit = NULL,
#MinPrice decimal(18, 0) = NULL,
#MaxPrice decimal(18, 0) = NULL,
#bedRoom smallint = NULL,
#PropertyType NVARCHAR(20) = NULL,
#requestType NVARCHAR(20) = NULL,
#Parking bit = NULL,
#RemoteParking bit = NULL,
#Lobby bit = NULL,
#AssemblyHall bit = NULL,
#Gym bit = NULL,
#Surveillance bit = NULL,
#FireAlarm bit = NULL,
#FireFighting bit = NULL,
#Pool bit = NULL,
#Sauna bit = NULL,
#Jacuzzi bit = NULL,
#Carwash bit = NULL,
#Laundry bit = NULL,
#Custodian bit = NULL,
#Shooting bit = NULL,
#TheftAlarm bit = NULL,
#PanelFit bit = NULL,
#Sentry bit = NULL,
#CentralSatellite bit = NULL,
#CentralAntenna bit = NULL,
#Fireplaces bit = NULL,
#MasterRoom bit = NULL,
#Patio bit = NULL,
#Barbecue bit = NULL,
#UPS bit = NULL,
#RoofGarden bit = NULL
AS
BEGIN
BEGIN TRY
SET NOCOUNT ON ;
BEGIN TRANSACTION;
DECLARE #CityId int;
IF EXISTS(SELECT Estate_CityId FROM [^Estate_City] WHERE Estate_CityName = #city)
BEGIN
SET #CityId= (SELECT Estate_CityId FROM [^Estate_City] WHERE Estate_CityName = #city);
END
IF(#MinPrice IS NOT NULL AND #MaxPrice IS NOT NULL)
BEGIN
IF (#MaxPrice>0 AND #MaxPrice>#MinPrice)
BEGIN
DECLARE #results TABLE (RowNum INT,Estate_Code BIGINT,Estate_propertyType NVARCHAR(50),Estate_buildingArea NVARCHAR(20),Estate_floor NVARCHAR(10),Estate_neighborhoodProperty NVARCHAR(100),Estate_street1 NVARCHAR(100),
Estate_street2 NVARCHAR(100),Estate_visits BIGINT,houseImage NVARCHAR(MAX),houseImage1 NVARCHAR(MAX),houseImage2 NVARCHAR(MAX),houseImage3 NVARCHAR(MAX),houseImage4 NVARCHAR(MAX),Owner_requestType NVARCHAR(MAX),
Facility_Description NVARCHAR(MAX),Estate_BedRoomCount NVARCHAR(2))
INSERT INTO #results(RowNum,Estate_Code,Estate_propertyType,Estate_buildingArea,Estate_floor,Estate_neighborhoodProperty,Estate_street1,Estate_street2,Estate_visits,houseImage,houseImage1,
houseImage2,houseImage3,houseImage4,Owner_requestType,Facility_Description,Estate_BedRoomCount)
SELECT ROW_NUMBER() OVER(ORDER BY [^Estate].Estate_Code) AS [Row],[^Estate].Estate_Code,[^Estate].Estate_propertyType, [^Estate].Estate_buildingArea,[^Estate].Estate_floor,[^Estate].Estate_neighborhoodProperty,[^Estate].Estate_street1,[^Estate].Estate_street2,[^Estate].Estate_visits,[^Estate_Images].houseImage,[^Estate_Images].houseImage1,[^Estate_Images].houseImage2,[^Estate_Images].houseImage3,[^Estate_Images].houseImage4,[^Estate_OwnerInfo].RequestType_Type,[^Estate_Facility].Facility_descText,[^Estate].Estate_bedRoomCount
FROM [^Estate]
INNER JOIN [^Estate_Images] ON [^Estate].Estate_Code=[^Estate_Images].Estate_Code
INNER JOIN [^Estate_OwnerInfo] ON [^Estate].Owner_code=[^Estate_OwnerInfo].Owner_code
INNER JOIN [^Estate_Facility] ON [^Estate].Estate_Code=[^Estate_Facility].Estate_Code
INNER JOIN [^Estate_City] ON [^Estate].Estate_CityId =[^Estate].Estate_CityId
WHERE
(#CityId IS NULL OR [^Estate].Estate_CityId =#CityId ) AND
(#requestType IS NULL OR [^Estate_OwnerInfo].RequestType_Type = #requestType) AND
([^Estate].Estate_totalPrice BETWEEN #MinPrice AND #MaxPrice) AND
(#bedRoom IS NULL OR [^Estate].Estate_bedRoomCount>#bedRoom) AND
(#PropertyType IS NULL OR [^Estate].Estate_propertyType = #PropertyType) AND
(#requestType IS NULL OR [^Estate_OwnerInfo].RequestType_Type = #requestType) AND
(#bedRoom IS NULL OR [^Estate].Estate_bedRoomCount = #bedRoom) AND
(#Parking IS NULL OR [^Estate_Facility].Facility_Parking = #Parking) AND
(#RemoteParking IS NULL OR [^Estate_Facility].Facility_RemoteParking = #RemoteParking) AND
(#Lobby IS NULL OR [^Estate_Facility].Facility_Lobby = #Lobby)AND
(#Gym IS NULL OR [^Estate_Facility].Facility_Gym = #Gym) AND
(#Surveillance IS NULL OR [^Estate_Facility].Facility_Surveillance = #Surveillance) AND
(#FireAlarm IS NULL OR [^Estate_Facility].Facility_FireAlarm = #FireAlarm) AND
(#FireFighting IS NULL OR [^Estate_Facility].Facility_FireFighting = #FireFighting) AND
(#Pool IS NULL OR [^Estate_Facility].Facility_Pool = #Pool) AND
(#Sauna IS NULL OR [^Estate_Facility].Facility_Sauna = #Sauna) AND
(#Jacuzzi IS NULL OR [^Estate_Facility].Facility_Jacuzzi = #Jacuzzi) AND
(#Carwash IS NULL OR [^Estate_Facility].Facility_Carwash = #Carwash) AND
(#Laundry IS NULL OR [^Estate_Facility].Facility_Laundry = #Laundry) AND
(#Custodian IS NULL OR [^Estate_Facility].Facility_Custodian = #Custodian) AND
(#Shooting IS NULL OR [^Estate_Facility].Facility_Shooting = #Shooting) AND
(#TheftAlarm IS NULL OR [^Estate_Facility].Facility_TheftAlarm = #TheftAlarm) AND
(#PanelFit IS NULL OR [^Estate_Facility].Facility_PanelFit = #PanelFit) AND
(#Sentry IS NULL OR [^Estate_Facility].Facility_Sentry = #Sentry) AND
(#CentralSatellite IS NULL OR [^Estate_Facility].Facility_CentralSatellite = #CentralSatellite) AND
(#CentralAntenna IS NULL OR [^Estate_Facility].Facility_CentralAntenna = #CentralAntenna) AND
(#Fireplaces IS NULL OR [^Estate_Facility].Facility_Fireplaces = #Fireplaces) AND
(#MasterRoom IS NULL OR [^Estate_Facility].Facility_MasterRoom = #MasterRoom) AND
(#Patio IS NULL OR [^Estate_Facility].Facility_Patio = #Patio) AND
(#Barbecue IS NULL OR [^Estate_Facility].Facility_Barbecue = #Barbecue) AND
(#UPS IS NULL OR [^Estate_Facility].Facility_UPS= #UPS) AND
(#RoofGarden IS NULL OR [^Estate_Facility].Facility_RoofGarden = #RoofGarden)
END
END
select * from #results order by Estate_Code;
DECLARE #ErrorCode INT;
DECLARE #Result INT;
SET #ErrorCode = ##ERROR;
IF (#ErrorCode <> 0)
BEGIN
ROLLBACK TRANSACTION;
SET #Result=0;
EXEC Debug_InsertSQLErrorDetails
END
ELSE
BEGIN
COMMIT TRANSACTION;
SET #Result=SCOPE_IDENTITY();
END
END TRY
BEGIN CATCH
SET NOCOUNT OFF
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION;
END
EXEC Debug_InsertSQLErrorDetails
SET #Result=0;
END CATCH
END
Please help me to solve this problem thanks!
First of all, a stored procedure will not run multiple times.
The reason could be thatfrom the Estate table you join multiple tables. If these joins are not 1 to 1, but 1 to n, you'll get a result row for each possible join.
Eg, if an Estate has multiple images, you'll get a row for each estate image in your result.
So I am making a very simple update procedure, like I have done before, but when I run the execution through it, it does not update. I have looked this over several times and do not see any error in why it wouldn't cause the update to pass through it. My manual updates are working fine, so I am thinking I am either missing something super-obvious or this is something going on with the coalesce function. Any help would be great. The more eyes the merrier.
USE AdventureWorks2012
GO
CREATE PROCEDURE UpdateCreditCard
#CreditCardID INT,
#CardType nvarchar(50) = NULL,
#CardNumber nvarchar(25) = NULL,
#ExpMonth tinyint = NULL,
#ExpYear smallint = NULL
AS
BEGIN
UPDATE [Sales].[CreditCard]
SET
#CardType = COALESCE(#CardType,CardType),
#CardNumber = COALESCE(#CardNumber,CardNumber),
#ExpMonth = COALESCE(#ExpMonth,ExpMonth),
#ExpYear = COALESCE(#ExpYear,ExpYear)
FROM Sales.CreditCard
WHERE #CreditCardID = CreditCardID
END
EXECUTE UpdateCreditCard
#CreditCardID = 19267,
#CardType = 'MasterCard',
#CardNumber = '99999999',
#ExpMonth = 4,
#ExpYear = 2025
You are updating the variables not the columns in CreditCard table.
.....
SET
#CardType = COALESCE(#CardType,CardType), -- here you are updating the #CardType variable
.....
Try this.
CREATE PROCEDURE UpdateCreditCard
#CreditCardID INT,
#CardType nvarchar(50) = NULL,
#CardNumber nvarchar(25) = NULL,
#ExpMonth tinyint = NULL,
#ExpYear smallint = NULL
AS
BEGIN
UPDATE [Sales].[CreditCard]
SET
CardType = COALESCE(#CardType,CardType),
CardNumber = COALESCE(#CardNumber,CardNumber),
ExpMonth = COALESCE(#ExpMonth,ExpMonth),
ExpYear = COALESCE(#ExpYear,ExpYear)
FROM Sales.CreditCard
WHERE CreditCardID=#CreditCardID
END
In SQL Server 2012, I have a script that call a stored procedure multiple times.. The loop will be executed as many times as the number of records in [ResultHeader] table.
EXEC [AS400].tp_SelectChildItems #Pgm, #Grp, #Pgmgrpseq,
null, null, null, null, null, #ItemSelection, null,
null, null, null, null,
Note: This SP has a table variable inside
I have a comma separated list of SelectedCostPageList. For each value in this list, the loop is executed once.
I am observing a weird behavior. When I invoke the sp from the script, only for the first time the sp is returning proper records.. On subsequent calls the stored procedure is returning no records. Very odd…. When I change the order of comma separated string, only for the first iteration the sp is returing records.. other times no records.
Any guess what will be the reason?
DECLARE #SelectedCostPageList VARCHAR(MAX)
SET #SelectedCostPageList = (SELECT (SELECT CONVERT(VARCHAR(32), A.PGM + '-'+A.GRP+'-'+A.PGMGRPSEQ) + ', ' AS [text()]
FROM dbo.[ResultHeader] A
WHERE UserId = 'U25703'
FOR XML PATH('')) AS CostPages) ResultHeader
PRINT #SelectedCostPageList
DECLARE #pos INT
DECLARE #len INT
set #pos = 0
set #len = 0
DELETE FROM ResultItems
WHILE CHARINDEX(',', #SelectedCostPageList, #pos+1)>0
BEGIN
set #len = CHARINDEX(',', #SelectedCostPageList, #pos+1) - #pos
DECLARE #SelectedCostPage VARCHAR(10)
set #SelectedCostPage = SUBSTRING(#SelectedCostPageList, #pos, #len)
set #pos = CHARINDEX(',', #SelectedCostPageList, #pos+#len) +1
PRINT #SelectedCostPage
DECLARE #Pgm AS VARCHAR (10);
DECLARE #Grp AS VARCHAR (10);
DECLARE #Pgmgrpseq AS VARCHAR (10);
SELECT #Pgm = (SELECT VALUE
FROM [AS400].[tf_SelectSplitString] (#SelectedCostPage, '-')
WHERE POSITION = 1);
PRINT #Pgm
SELECT #Grp = (SELECT VALUE
FROM [AS400].[tf_SelectSplitString] (#SelectedCostPage, '-')
WHERE POSITION = 2);
PRINT #Grp
SELECT #Pgmgrpseq = (SELECT VALUE
FROM [AS400].[tf_SelectSplitString] (#SelectedCostPage, '-')
WHERE POSITION = 3);
PRINT #Pgmgrpseq
Declare #ItemSelection as varchar(4000)
set #ItemSelection ='1116102540,1116102541';
print #ItemSelection
print 'HAI'
print #Pgmgrpseq
EXEC [AS400].tp_SelectChildItems
#Pgm, #Grp, #Pgmgrpseq,
null, null, null,
null, null, #ItemSelection, null,
null, null, null, null,
null, null, null, 1, 'U25703'
END
SELECT * FROM ResultItems
WHERE UserId = 'U25703'
If I had to guess, it would be because you are using ', ' (comma followed by a space) as a list separator, but the code is just looking for a comma. You would then have a leading space on a string value, which, presumably, would not then match whatever needs to be matched.
The first works, because you initialize the list string with a comma without a space.
Perhaps more importantly, I find the approach of stuffing things into a string to loop over them to be, shall I say, very 1980s. You could use a cursor (not my favorite approach) or a temporary table. When I want to do loops over such data, I sometimes structure them as follows:
declare #looptable table (rownum int identity(1, 1), . . . );
insert into #looptable . . .;
declare #tot int;
select #tot = count(*) from #looptable;
declare #i int = 1;
while (#i <= tot)
begin
-- something here with "where rownum = #i"
end;
The idea of stuffing values into a string just to write more code to parse them out seems like a waste of programming effort. In addition, this can cause problems because of the conversion of types into character formats and the obscene ways that for path xml handles characters such as '<' and '>'.