In my stored procedure, when a long word is passed, server shows error, with part of the word.
I am not sure what is happening .. the word seems to break, but I have given a big value for that variable
My procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_BuyOnlineSearchNew]-- '1','BMW X6 IN GOOD CONDITION FOR SALE','0','0'
#CategoryID varchar(20),
#SearchString varchar(max),
#RecentAd int,
#RowsPerPage INT,
#PageNumber INT,
#pricefrom INT,
#priceto INT,
#categories Varchar(2000),
#advancesearch varchar(2000),
#features varchar(2000),
#technicalfeatures varchar(2000),
#CompanyID varchar(20)
AS
BEGIN
SET NOCOUNT ON;
declare #OffetCount as int = (#PageNumber-1)*4
Select TotalCount = COUNT(CM.BuyOnlineID) OVER(),
CM.BuyOnlineID,cm.OfferPrice,cm.[Description], CM.Title,CONVERT(VARCHAR, [CM].[DatePosted],106) AS 'DatePosted',
CM.Price,
CM.isActive,
CM.GoogleLocation,
CM.IsImageVerified,
Row_Number() Over ( Order By CM.BuyOnlineID desc ) As Rownumber,
CM.AreaID,
(select top 1 image from [tblBuyOnlineImages] where BuyOnlineID=CM.BuyOnlineID) As imagepath,
(select count(*) from [tblBuyOnlineImages] where BuyOnlineID=CM.BuyOnlineID) As imagecount,
CM.categorytreename
FROM [dbo].[tblBuyOnlineMaster] AS CM
WHERE
(CONTAINS(CM.CategoryTreename, #categories))
order by CM.BuyOnlineID OFFSET #OffetCount ROWS FETCH NEXT 4 ROWS ONLY
SET NOCOUNT OFF
END
Related
I am using an SSRS multi-select which gives me an unknown number of values > 0. That is something like the following (1),(4),...(x).
I want to union the results of a stored procedure for each ID that SQL receives.
If this came as a table my job would be easier.
ID
1
4
...
x
I found the following code got me a good way there:
DECLARE #MyTempTable TABLE (txtType NVARCHAR(20), intID integer, txtAccountCode NVARCHAR(50), txtSchoolID NVARCHAR(50), txtSageCode NVARCHAR(50), ChargeCode NVARCHAR(50),
txtDescription NVARCHAR(200), mAmount DECIMAL(18,2), percentageAmount DECIMAL(18,2), txtChargeType NVARCHAR(50), txtNominalAccount NVARCHAR(50), bBilledInAdvance BIT)
DECLARE #i int
DECLARE #CycleId int
DECLARE #numrows int
DECLARE #Cycle Table (
idx smallint IDENTITY(1,1)
, CycleId int
)
INSERT #Cycle (CycleId)
SELECT [TblFeeBillingCycleID] FROM [TblFeeBillingCycle] WHERE [TblFeeBillingCycleID] IN(#intCycleId)
SET #i = 1
SET #numrows = (SELECT COUNT(*) FROM #Cycle)
IF #numrows > 0
WHILE (#i <= (SELECT MAX(idx) FROM #Cycle))
BEGIN
SET #CycleId = (SELECT CycleId FROM #Cycle WHERE idx = #i)
INSERT INTO #MyTempTable
EXEC usp_cust_GetTransactionsByCycle #CycleId
SET #i = #i + 1
SET #i = #i + 1
END
If I could either unpivot my row of unknown length and unknown columns then this would work I think.
I also thought there was a way to insert into a table by wrapping values, so it chops a long row of data into x rows matching the length of the new table.
Then again there may be another way to iterate up a table of unknown length and unknown columns names.
SQL might be the wrong way to go, I just fear SSRS is pushing me in this direction, I don't know if I can do the foreach in SSRS instead.
If the question is about how to transform string into table then yuo can use STRING_SPLIT
DECLARE #InString VARCHAR(20);
SET #InString='1,2,3,4,5,6,7,8,9,10';
SELECT VALUE FROM string_split(#InString,',');
I think it's a kind of madness but I found a workaround to get a table of values from the results from SSRS. I query the IDs against a source table using IN().
SELECT [TblFeeBillingCycleID]
FROM [TblFeeBillingCycle]
WHERE [TblFeeBillingCycleID] IN(#intCycleId)
Code:
Declare #ParmDefinition Nvarchar(1000),
#St Nvarchar(500),
#TTable varchar(30)
Set #TTable='[0Detail]'
Declare #TTempStore Table (
Iden Int,
Row_ Int,
Accs_iden int,
Am_Bed Money,
Am_Bes Money,
Doc_No Decimal(15,0),
Desc_ Nvarchar(500),
Checked bit,
Error_ int)
SET #ParmDefinition = N'#alaki table(Iden Int,
Row_ Int,
Accs_iden int,
Am_Bed Money,
Am_Bes Money,
Doc_No Decimal(15,0),
Desc_ Nvarchar(500),Checked bit,Error_ int) OUTPUT '
Set #St = N' Select * into #alaki from '+#TTable
EXECUTE sp_executesql #St, #ParmDefinition, #alaki = #TTempStore
SELECT * FROM #TTempStore
Errors:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'table'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '#alaki'.
You should post a minimal working sample for us to be able to help you, remember that next time.
Why not declare the table with #TTempStore ?
Declare #St Nvarchar(500),#TTable varchar(30)
Set #TTable='[0Detail]'
create table #TTempStore (
Iden Int,
Row_ Int,
Accs_iden int,
Am_Bed Money,
Am_Bes Money,
Doc_No Decimal(15,0),
Desc_ Nvarchar(500),
Checked bit,
Error_ int)
Set #St=N' Select * into #TTempStore from '+#TTable
EXECUTE #St
Select * from #TTempStore
drop table #TTempStore --here you can leave the table if you have more things to do
I haven't tested it, but it should point you in the right direction. If you need I can probably make a sql fiddle later.
Could the #TTable value be different every time? If it's always going to be [0Detail] then you don't need dynamic SQL. However, here is a dynamic SQL solution to your problem:
Declare #St Nvarchar(500),#TTable varchar(30)
Set #TTable='[0Detail]'
Declare #TTempStore Table (
Iden Int,
Row_ Int,
Accs_iden int,
Am_Bed Money,
Am_Bes Money,
Doc_No Decimal(15,0),
Desc_ Nvarchar(500),
Checked bit,
Error_ int)
Set #St=N' Select * from '+#TTable
INSERT INTO #TTempStore
EXECUTE (#St)
Select * from #TTempStore
I have a stored procedure I have created so that I can enter lines into a table and subsequently return the INSERTED.ID so I can return this ID to the SQL Command that sent it to input the ID into that table.
I have used OUTPUT INSTEAD.ID before and this works fine when I do it as just an insert statement but how do I get the same result with a Stored Procedure.
I have done the following but can't seem to get it to output correctly.
CREATE PROCEDURE sp_XStream_Send
-- Add the parameters for the stored procedure here
#Dept VARCHAR(30),
#Process VARCHAR,
#RequestDT DATETIME,
#RequestType VARCHAR,
#RequestBranch INT,
#RequestPolRef VARCHAR,
#RequestXML VARCHAR,
#ReturnID INT OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #OutputTbl TABLE (ID INT)
INSERT INTO dbo.XStream_Log
( Department ,
Process ,
RequestDT ,
RequestType ,
RequestBranch ,
RequestPolicyRef ,
RequestXML
)
OUTPUT INSERTED.ID INTO #OutputTbl(ID)
VALUES ( #Dept,
#Process,
#RequestDT,
#RequestType,
#RequestBranch,
#RequestPolRef,
#RequestXML
)
SELECT #ReturnID = ID FROM #OutputTbl
RETURN
END
GO
When i do the EXEC it wants me to send the #ReturnID but I don't want to Input anything into it, I want the output of the inserted ID.
Any help, cheers.
UPDATE
I am executing my stored procedure like so:
DECLARE #ID INT;
EXEC dbo.sp_XStream_Send #Dept = 'IT', -- varchar(1)
#Process = 'XStream Test', -- varchar(1)
#RequestDT = '2016-05-09 09:28:38', -- datetime
#RequestType = 'create-broomsrisk', -- varchar(1)
#RequestBranch = 0, -- int
#RequestPolRef = 'POMS01PC01', -- varchar(1)
#RequestXML = '<TestXML></TestXML>', -- varchar(1)
#ReturnID = #ID OUTPUT;
I am just getting 'Command(s) completed successfully' and not the actual ID.
I have created a trigger for a asset_verification. Whenever a new record is inserted in this table, the same record is inserted in the asset_verification_history table because of this trigger.
The trigger is as follows
Create trigger [dbo].[tr_insert_after_asset_verification] on [dbo].[asset_verification]
for insert
As
Begin
declare #verification_id int
declare #id int
declare #audit_id int
declare #date date
declare #status varchar(15)
declare #remarks varchar(200)
declare #creationDate datetime
declare #modificationDate datetime
declare #updatedBy int
declare #audit_action varchar(20)
Select #verification_id = i.verification_id from inserted i
If #verification_id IS NOT NULL
Begin
Select #id = i.id from inserted i
Select #audit_id = i.audit_id from inserted i
Select #date = i.date from inserted i
Select #status = i.status from inserted i
Select #remarks = i.remarks from inserted i
Select #creationDate = i.creationDate from inserted i
Select #modificationDate = i.modificationDate from inserted i
Select #updatedBy = i.updatedBy from inserted i
set #audit_action = 'Insert Record'
INSERT INTO [dbo].[asset_verification_history]
([verification_id]
,[id]
,[audit_id]
,[date]
,[status]
,[remarks]
,[creationDate]
,[modificationDate]
,[updatedBy]
,[audit_action])
VALUES
(#verification_id
,#id
,#audit_id
,#date
,#status
,#remarks
,#creationDate
,#modificationDate
,#updatedBy
,#audit_action)
End
End
When I insert the data in the asset_verification table using a procedure in which OPEN XML is used, then this trigger works only for the first record. For the rest of the records the trigger doesn't work
The procedure is as follows
Create procedure [dbo].[usp_AddVerificationBulkData]
(
#vXML XML
)
As
Begin
DECLARE #DocHandle INT
SET NOCOUNT ON
EXEC sp_xml_preparedocument #DocHandle OUTPUT, #vXML
Update asset_verification
set
audit_id = x.AuditId,
id = x.SerialId,
date = x.VerificationDate,
status = x.Status
,remarks = x.Remarks
,creationDate = x.CreatedOn
,modificationDate = x.ModifiedOn
,updatedBy = x.ModifiedBy
From
asset_verification a
Inner Join
OpenXml(#DocHandle,'/ArrayOfAssetVerificationModel/AssetVerificationModel',2)
With(SerialId int, AuditId int, VerificationDate datetime, Status int, Remarks varchar(200), CreatedOn datetime, ModifiedOn datetime, ModifiedBy int) x
On a.audit_id = x.AuditId where a.id = x.SerialId;
INSERT INTO [dbo].[asset_verification]
([id]
,[audit_id]
,[date]
,[status]
,[remarks]
,[creationDate]
,[modificationDate]
,[updatedBy])
select SerialId,AuditId,VerificationDate,Status,Remarks,CreatedOn,ModifiedOn,ModifiedBy from OpenXml(#DocHandle,'/ArrayOfAssetVerificationModel/AssetVerificationModel',2)
With(SerialId int, AuditId int, VerificationDate datetime, Status int, Remarks varchar(200), CreatedOn datetime, ModifiedOn datetime, ModifiedBy int) x
where SerialId NOT IN (select a.id from asset_verification a where a.audit_id = x.AuditId);
End
Problem:- How to make this trigger work for every record that is inserted through Open XML ?
You've made the classic mistake of thinking that triggers fire once-per-row. They dont, it's once-per-action, so the inserted pseudo table holds all the rows affected by the action. Your trigger needs to work in a set based manner, not row based. Try this;
CREATE TRIGGER [dbo].[tr_insert_after_asset_verification] ON [dbo].[asset_verification] FOR INSERT AS
BEGIN
SET NOCOUNT ON
INSERT INTO [dbo].[asset_verification_history]
( [verification_id]
,[id]
,[audit_id]
,[date]
,[status]
,[remarks]
,[creationDate]
,[modificationDate]
,[updatedBy]
,[audit_action]
)
SELECT i.verification_id
,i.id
,i.audit_id
,i.date
,i.status
,i.remarks
,i.creationDate
,i.modificationDate
,i.updatedBy
,'Insert Record'
FROM inserted i
WHERE i.verification_id IS NOT NULL
END
As an aside, and strictly speaking, your original trigger will log one row, not necessarily the first.
I have two stored procedures as follows:
create stored procedure p1
as
select * from table1 where datediff(day, table1.[date], getdate())
create stored procedure p2
as
declare #t1 table(
ref varchar(20)
)
insert into #t1 select * from table1 where ref = 'some ref'
declare #t2 table(
fname varchar(20),
lname varchar(20),
email varchar(1000)
)
declare #len int = (select count(ref) from #t1)
while #len > 0
begin
declare #value varchar(20) = (select top 1 ref from #t1)
insert into #t2 select * from table2 where ref = #ref
delete from #t1
where ref = #value
set #len = (select count(ref) from #t1)
end
select * from #t2
Java code
....
String query = "Execute [p2]";
try(CallableStatement cstmt = conn.prepareCall(query);
ResultSet rs = cstmt.executeQuery()){
... some code
}
The table variable #t1 hold select result from a table 'table1'
The variable #len hold the number of rows in #t1
Using #len > 0 as condition in while loop, I want to select records from another table 'table2' the table variable #t2 hold the select records from 'table2'
The delete statement removes value from #t1
#len set to new number of rows in #t1
the last statement return all the records store in #t2
The first procedure works fine, but the second procedure works only in SQL Server.
I get this an error message in my java application
statement did not return a resultset
I want this to return a result set with the select statement I have at the
end of the query.
Please is there a way around this?
Your [p2] stored procedure needs to include SET NOCOUNT ON right at the beginning to suppress the "n rows affected" counts so JDBC doesn't get confused as to what it should put into the ResultSet:
CREATE PROCEDURE p2
AS
SET NOCOUNT ON;
declare #t1 table(
ref varchar(20)
)
-- ... and so on
For more information on SET NOCOUNT see
SET NOCOUNT (Transact-SQL)
For more information on precisely what gets returned from a stored procedure call, see
How to get everything back from a stored procedure using JDBC
use method "execute" instead of "executeQuery".