Stored procedure not accepting any value - sql-server

I have written a stored procedure based on a set of process, I'm just passing a single parameter as input to the procedure but it seems it is not taking the value. But when I give input value instead of parameter in the procedure it is working.
There is no mistake in the flow of process, but seems something missing in the procedure syntax end.
below is the stored procedure I used.
ALTER PROCEDURE [TransferIn]
#ponumber NVARCHAR = NULL
AS
BEGIN
--step 1 Delete Temp Pur_ID
IF EXISTS (
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'Pur_ID_IN')
DROP TABLE Pur_ID_IN;
-- =============================================
--step 2 select PO Number
--IF #ponumber IS NOT NULL
SELECT
ponumber, id
INTO Pur_ID_IN
FROM purchaseorder
WHERE potype IN (2, 4)
AND status = 0
AND ponumber = #ponumber;
-- =============================================
--step 3
--delete Temp. Tabel P_Test20_12_IN
IF EXISTS (
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'P_Test20_12_IN')
DROP TABLE P_Test20_12_IN;
-- =============================================
-- step 4 (Insert Data For Invoice To Temp Tabel After Group )
SELECT
ItemDescription, PurchaseOrderID,
SUM(QuantityOrdered) AS QuantityOrdered,
itemid, Price
INTO P_Test20_12_IN
FROM PurchaseOrderEntry
WHERE PurchaseOrderID IN (SELECT id FROM Pur_ID_IN)
GROUP BY
ItemDescription, StoreID, PurchaseOrderID,
itemid, Price;
--order by 3
-- =============================================
-- step 5 Delete Record From PurchaseOrderEntry
DELETE PurchaseOrderEntry
FROM PurchaseOrderEntry
WHERE PurchaseOrderID IN (SELECT id FROM Pur_ID_IN);
-- =============================================
INSERT INTO [W07].[dbo].[PurchaseOrderEntry] ([ItemDescription], [LastUpdated], [PurchaseOrderID], [QuantityOrdered], [ItemID], [Price])
SELECT
[ItemDescription],
GETDATE() AS [LastUpdated],
[PurchaseOrderID], [QuantityOrdered],
[ItemID], [Price]
FROM
P_Test20_12_IN;
END

Problem is
#ponumber nvarchar = null
change it to
#ponumber nvarchar(max) = null
Note:If you do NOT specify the size(char, nchar, varchar, nvarchar),
sql server will default to 1 character.

ALTER PROCEDURE [TransferIn]
(
#ponumber NVARCHAR(100)
)
AS BEGIN
SET NOCOUNT ON
IF OBJECT_ID('tempdb.dbo.#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp (id INT PRIMARY KEY)
INSERT INTO #temp (id)
SELECT /*DISTINCT*/ id
FROM dbo.purchaseorder
WHERE potype IN (2, 4)
AND [status] = 0
AND ponumber = #ponumber
IF OBJECT_ID('tempdb.dbo.#temp2') IS NOT NULL
DROP TABLE #temp2
SELECT ItemDescription,
PurchaseOrderID,
SUM(QuantityOrdered) AS QuantityOrdered,
itemid,
Price
INTO #temp2
FROM PurchaseOrderEntry
WHERE PurchaseOrderID IN (SELECT * FROM #temp)
GROUP BY ItemDescription,
StoreID, --?
PurchaseOrderID,
itemid,
Price;
DELETE PurchaseOrderEntry
FROM PurchaseOrderEntry
WHERE PurchaseOrderID IN (SELECT * FROM #temp)
INSERT INTO [W07].[dbo].[PurchaseOrderEntry] ([ItemDescription], [LastUpdated], [PurchaseOrderID], [QuantityOrdered], [ItemID], [Price])
SELECT [ItemDescription],
GETDATE() AS [LastUpdated],
[PurchaseOrderID],
[QuantityOrdered],
[ItemID],
[Price]
FROM #temp2
END

Related

Why I am getting Column Name Missing error

I wrote a SP which will call internally another parameterized SP and output will be store into a physical table.While I am executing Outer SP I am getting following error.
Msg 207, Level 16, State 1, Procedure CBs_LargeExposer, Line 88 [Batch
Start Line 12] Invalid column name 'SlNo'.
I observed, if I execute inner SP in separate window and very next to it if I execute the same outer SP is working fine, after certain time if I execute the same statement(Outer SP) I am getting same error.
ALTER PROCEDURE [dbo].[CBS_GlMapping]
#finYear nvarchar(30)='2019-2020',
#quarter char(5)='Q2',
#Oflag Varchar(6)='O4'
AS
BEGIN
SET NOCOUNT ON;
Declare #QtrStart date,#QtrSEnd date,#FyFrom int,#FyTo int,#BranchId int
select #FyFrom=year(YearBeginDate),#FyTo=Year(YEarEndDate) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
IF(#FyFrom < left(#finYear,4) and #FyTo < Right(#finYear,4))
Begin
print 'Sorry, Recods are not available for the financial year ' + #finYear
return
End
If(#quarter='Q1')
Begin
select #QtrStart=YearBeginDate,#QtrSEnd=EOMONTH(DATEADD(MM,2,YearBeginDate)) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
If(#quarter='Q2')
Begin
select #QtrStart=Dateadd(mm,3,YearBeginDate),#QtrSEnd=EOMONTH(DATEADD(MM,5,YearBeginDate)) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
If(#quarter='Q3')
Begin
select #QtrStart=Dateadd(mm,6,YearBeginDate),#QtrSEnd=EOMONTH(DATEADD(MM,8,YearBeginDate)) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
If(#quarter='Q4')
Begin
select #QtrStart=DATEADD(month, DATEDIFF(month, 0,Dateadd(mm,-2,YEarEndDate)), 0),#QtrSEnd=YEarEndDate from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
/* To handel the Financial year */
if(left(#finYear,4)<year(#QtrStart) and #quarter<>'Q4')
begin
set #QtrStart = cast(left(#finYear,4) as varchar(4))+'-'+cast(month(#QtrStart) as Varchar(2))+'-'+Cast(day(#QtrStart) as Varchar(2))
set #QtrSEnd = cast(left(#finYear,4) as varchar(4))+'-'+cast(month(#QtrSEnd) as Varchar(2))+'-'+Cast(day(#QtrSEnd) as Varchar(2))
end
if(right(#finYear,4)<year(#QtrStart) and #quarter='Q4')
begin
set #QtrStart = cast(right(#finYear,4) as varchar(4))+'-'+cast(month(#QtrStart) as Varchar(2))+'-'+Cast(day(#QtrStart) as Varchar(2))
set #QtrSEnd = cast(right(#finYear,4) as varchar(4))+'-'+cast(month(#QtrSEnd) as Varchar(2))+'-'+Cast(day(#QtrSEnd) as Varchar(2))
end
Create table #tempData
(
Bal numeric(15,2)
)
declare #sql varchar(500),#sql2 varchar(500),#day Varchar(10),#Month varchar(2),#Year varchar(4)
select #day= Day(#QtrSEnd)
select #Month= month(#QtrSEnd)
select #Year= Year(#QtrSEnd)
Create table #temp
( slno int,
glcode Varchar(500),
GlLen int,
ColNO varchar(50),
CellNo varchar(50),
Amount Numeric(15,2)
)
declare #tsql varchar(500)
set #tsql=N'
insert into #temp
select ROW_NUMBER() over(order by glcode) slno,glcode,LEN(Glcode) GlLen,ColNo,CellNo,amount
from BsGl'+#Oflag+'
where glcode <>'''' '
exec(#tsql)
declare #LoopStart int,#loopEnd Int,#glcode varchar(500),#amt numeric(15,0)
select #LoopStart=Min(Slno) from #temp
select #loopEnd=MAX(Slno) from #temp
while (#LoopStart <= #loopEnd)
begin
select #glcode= Glcode from #temp where slno = #LoopStart
set #sql='insert into #tempData select Sum(day'+#day+') from DayBal where AcYear='+#Year+' and acmonth='+#Month+'and GlCode in(SELECT glcode FROM dbo.splitstring(convert(varchar(500),'''+#glcode+''')))'
EXEC(#sql)
update #temp set Amount=(select Bal from #tempData) where slno =#LoopStart
set #LoopStart=#LoopStart+1
Truncate table #tempData
end
set #tsql=''
set #tsql='update BsGl'+#Oflag+' set Amount=0.00 where Glcode ='''' '
EXEC(#tsql)
set #tsql=''
set #tsql='update B set B.amount=isnull(round((Case when A.Amount<0 then A.Amount*(-1) else A.Amount end/1000),0),0) from #temp a inner join BsGl'+#Oflag+' B on a.CellNo=B.CellNo and B.ColNo=A.ColNo'
EXEC(#tsql)
IF(#Oflag='O4')
BEGIN
EXEC [DBO].[CBs_LargeExposer] #QtrSEnd
END
Drop table #temp
End
Not sure if you have tried this already. Try specifying the exact same column name "slno" as in CREATE TABLE statement, in the below two SELECT statements, instead of "Slno".
select #LoopStart=Min(Slno) from #temp
select #loopEnd=MAX(Slno) from #temp
I found the Solution for the error. I created same #temporary table in outer sp as well as in inner sp with different columns. Basically a #temporary table's scope is limited to the session but when you are calling a inner Sp inside a outer sp it will consider a single session.
Outer SP TempTable Declaration
Create table #tempData
(
Bal numeric(15,2)
)
Inner SP TempTable Declaration
CREATE TABLE #tempData(
[ID] int identity(1,1) ,
[Funded] [numeric](15, 2) NOT NULL,
[NonFunded] [numeric](2, 2) NOT NULL,
[Limitsanctioned] [numeric](15, 2) NOT NULL
)
So I changed the #tmpData to #tempData1 in outer Sp it's working fine.

How can i handle Insert from select statement using trigger in sqlserver

I have the following TSQL statements to insert data from one database Table to another database tables, how can i mange this using Trigger?
the Source table is [DISCS] and the destination tables are,
[WIBOMH] is a Master table, [WIBOMH] is a header table, [WIBOMD] is detail table so
the orders have to be first insert into [WIITEM] then create a header [WIBOMH]
I want to fire this AFTER INSERT. when i added a new DISC into DISC Table i would like to fire the following insert statement
-- Insert into [WIITEM] Table---
INSERT INTO [WIITEM]
([itemId], [descr],[xdesc],[sales] ,[uOfM] ,[poUOfM] ,[uConvFact],[ref],[type],[status],[unitWgt] )
SELECT [itemId], [PURCHASE_DESCRIPTION], [SALES_DESCRIPTION], [sales] ,[uOfM] ,[poUOfM] ,[uConvFact],'TESTING', '2','0',[unitWgt]
FROM [DISCS]
WHERE [itemId] NOT IN (SELECT [itemId] FROM [WIITEM])
AND [makebuy]='Make';
-- Insert into [WIBOMH] Table---
DECLARE #d DATETIME = GETDATE();
INSERT INTO [WIBOMH]
([bomItem], [bomRev], [rollup], [mult], [autoBuild], [assyLead],[revCmnt],[author],[descr],[qPerLead],[lstMainDt],[revDate],[effStartDate],[ovride] )
SELECT DISTINCT [bomitem], 'B', '1', '1', '1', '3','TESTING','USER NAME','TESTING','0', FORMAT(#d, 'yyyy-MM-dd HH\:mm\:ss\.fff', 'en-US') AS 'Format#1',FORMAT(#d, 'yyyyMMdd' , 'en-US') AS 'Format#2',FORMAT(#d, 'yyyyMMdd' , 'en-US') AS 'Format#2','0'
FROM [DISCS]
WHERE [bomitem] IN (SELECT [ItemId] FROM [WIITEM] where type='2')
AND [bomitem] NOT IN (SELECT [bomItem] FROM [WIBOMH]);
-- Insert into [WIBOMD] Table---
INSERT INTO [WIBOMD]
([bomItem], [bomRev], [bomEntry], [partId], [qty],[cmnt],[srcLoc],[dType],[lead],[lineNbr])
SELECT [ItemID], 'B', [bomEntry], [partid], [qty],'TESTING','WSD-DS','0','0', [lineNbr]
FROM [DISCS]
WHERE [ItemID] IN (SELECT [ItemId] FROM [WIITEM] where type='2')
AND [ItemID] NOT IN (SELECT [bomItem] FROM [WIBOMD]);
i tried
INSERT INTO [MITESTCO].[WIITEM]
([itemId], [descr],[xdesc],[sales] ,[uOfM] ,[poUOfM] ,[uConvFact],[ref],[type],[status])
SELECT
[CALC STOCK PN], [PURCHASE DESCRIPTION], [SALES DESCRIPTION], [CALC STOCK PN] ,'EA' ,'EA' ,'1','SYNC FROM PDM', '2','0'--,[APPROX. WGT.]
FROM inserted
WHERE [MAKE / BUY]='Make' [CALC STOCK PN] NOT IN (SELECT [itemId] FROM [MIITEM] WHERE itemId NOT LIKE '*-CI');
but i get
invalid object [MITESTCO].[WIITEM]
here i got the first trigger working
create TRIGGER [dbo].[PNSETUP]
ON [dbo].[DISCS]
AFTER insert,UPDATE
AS
BEGIN
IF TRIGGER_NESTLEVEL() > 1
RETURN
SET ANSI_WARNINGS OFF;
INSERT INTO MITESTCO.dbo.WIITEM
([itemId], [descr],[xdesc],[sales] ,[uOfM] ,[poUOfM] ,[uConvFact],[ref],[type],[status])--,[unitWgt]
SELECT [CALC STOCK PN], [PURCHASE DESCRIPTION], [SALES DESCRIPTION], [CALC STOCK PN] ,'EA' ,'EA' ,'1','SYNC FROM PDM', '2','0'--,[APPROX. WGT.]
FROM [DISCS]
WHERE [CALC STOCK PN] NOT IN (SELECT [itemId] FROM MITESTCO.dbo.[WIITEM] WHERE itemId NOT LIKE '*-CI')
AND [MAKE / BUY]='Make';
SET ANSI_WARNINGS ON;
how can i add the next two insert select statement to same trigger
You can use after insert trigger to update the count after each insertion.
Do you need a trigger ? Do you need to copy the new rows from the table in real time ?
Triggers will KILL the insert performance of your table.
Consider adding a column DateLastCopied to the source table, and then once a minute
declare #now as datetime= getdate()
update sourcetable set DateLastCopied=#now where DateLastCopied is null
insert into targetTable(..)
select ...
FROM sourcetable where DateLastCopied=#now

How to DISPLAY horizontal data into vertical columns in SQL?

I have tables Employees, Documents, Transactions, from_to table.
Employee can send a document to other employee and send a copy of the document to other employee.
data will be displayed in transaction table as follow:
TransId - Document Id - EmployeeId - from_toId
1 1 5 1 (From)
2 1 6 2 (To)
3 1 10 2 (CC)
Now; I want the data above to be displayed as follow:
DocId From To CC
1 Jo(5) Fo(6) Do(10)
I know that we need something to do with "Pivot Table". BUT I DON'T KNOW HOW.
Waiting for your feedback.
I have a solution with a Cursor which is dynamic:
CREATE TABLE #PRERESULT(
[TransId] int,
DocumentID int ,
EmployeeId int ,
from_toId [nvarchar](10)
)
INSERT INTO #PRERESULT ([TransId],DocumentID,EmployeeId,from_toId)
VALUES
(1,1,5,'1 (From)'),
(2,1,6,'2 (To)'),
(3,1,10,'2 (CC)')
CREATE TABLE #RESULT (
DocID int,
[From] nvarchar(15),
[To] nvarchar(15),
CC nvarchar(15))
INSERT INTO #RESULT (DocID)
SELECT DocumentID
FROM #PRERESULT
GROUP BY DocumentID
DECLARE #Documentid int,#Employee int, #Alias nvarchar(10),#SQL nvarchar(250)
DECLARE C_FromTo CURSOR
FOR
SELECT DocumentID,EmployeeID
FROM #PRERESULT
OPEN C_FromTo
FETCH NEXT FROM C_FromTo INTO #Documentid, #Employee
While (##Fetch_status = 0)
BEGIN
SET #Alias = (SELECT SUBSTRING(from_toId,PATINDEX('%(%',from_toId)+1,(LEN(from_toId)-PATINDEX('%(%',from_toId)-1)) FROM #PRERESULT WHERE #Employee = EmployeeId)
SET #SQL = 'UPDATE #RESULT
SET ['+#Alias+'] = '+Convert(nvarchar(50),#Employee)+'
WHERE '+Convert(nvarchar(50),#Documentid)+' = DocID'
EXEC (#SQL)
FETCH NEXT FROM C_FromTo INTO #Documentid, #Employee
END
CLOSE C_FromTo
DEALLOCATE C_FromTO
SELECT * FROM #RESULT
DROP TABLE #PRERESULT
DROP TABLE #RESULT
Gives you this:
DocID |From |To |CC
1 |5 |6 |10
Hope this will help you
Have a nice day & Greets from Switzerland
Etienne
I think this reflects your table, although I am using names instead of IDs for the last two columns:
CREATE TABLE [dbo].[Transaction](
[TransId] [int] NOT NULL,
[DocId] [int] NOT NULL,
[EmpId] [nvarchar](10) NOT NULL,
[FromToId] [nchar](10) NOT NULL
) ON [PRIMARY]
INSERT INTO [Transaction] ([TransId],[DocId],[EmpId],[FromToId])VALUES(1,1,'Jo','From')
INSERT INTO [Transaction] ([TransId],[DocId],[EmpId],[FromToId])VALUES(2,1,'Fo','To')
INSERT INTO [Transaction] ([TransId],[DocId],[EmpId],[FromToId])VALUES(3,1,'Do','CC')
INSERT INTO [Transaction] ([TransId],[DocId],[EmpId],[FromToId])VALUES(4,2,'Jo','From')
INSERT INTO [Transaction] ([TransId],[DocId],[EmpId],[FromToId])VALUES(5,2,'Bo','To')
INSERT INTO [Transaction] ([TransId],[DocId],[EmpId],[FromToId])VALUES(6,2,'Zo','CC')
INSERT INTO [Transaction] ([TransId],[DocId],[EmpId],[FromToId])VALUES(7,3,'Bo','From')
INSERT INTO [Transaction] ([TransId],[DocId],[EmpId],[FromToId])VALUES(8,3,'Go','To')
Then this query will give you the results you requested:
SELECT DISTINCT
t.DocId
,x.[From]
,y.[To]
,z.Cc
FROM [Transaction] t
LEFT JOIN
(
SELECT DocId
,CASE WHEN FromToId = 'From' THEN EmpId END AS [From]
FROM [Transaction]
WHERE CASE WHEN FromToId = 'From' THEN EmpId END IS NOT NULL
) x ON t.DocId = x.DocId
LEFT JOIN
(
SELECT DocId
,CASE WHEN FromToId = 'To' THEN EmpId END AS [To]
FROM [Transaction]
WHERE CASE WHEN FromToId = 'To' THEN EmpId END IS NOT NULL
) y ON t.DocId = y.DocId
LEFT JOIN
(
SELECT DocId
,CASE WHEN FromToId = 'CC' THEN EmpId END AS [Cc]
FROM [Transaction]
WHERE CASE WHEN FromToId = 'Cc' THEN EmpId END IS NOT NULL
) z ON t.DocId = z.DocId
DocId From To Cc
1 Jo Fo Do
2 Jo Bo Zo
3 Bo Go NULL

Delete from source table then insert to target table if not exists

Need to delete all rows from a source table , then insert the deleted rows to target table
ONLY if the deleted row doesn't exists yet in the target table.
Is it possible to issue using a single sql?
Code is the one I tried so far (though with error).
Thank You!
create table #Target (column01 varchar(100)
,employee_number varchar(10)
)
Insert into #Target (column01, employee_number)
values ('2','222')
create table #Srs (column01 varchar(100)
,employee_number varchar(10)
)
Insert into #Srs (column01, employee_number)
values ('1','111')
,('2','222')
,('3','333')
,('4','444')
;with cteTable as (Select column01, employee_number from #Srs)
insert into #Target (column01, employee_number)
select * from (Delete from cteTable output deleted.column01, deleted.employee_number) t
where not exists (select 1
from #Target t1
where t1.employee_number = t.employee_number)
The 2,'222' should not be inserted into #Target on call to ";with cteTable.."
SQL FIDDLE DEMO
Composable DML is quite limited.
You can do this if you change the definition of #Target though
CREATE TABLE #Target
(
column01 VARCHAR(100),
employee_number VARCHAR(10) PRIMARY KEY WITH (IGNORE_DUP_KEY=ON)
)
INSERT INTO #Target
(column01,
employee_number)
VALUES ('2',
'222')
CREATE TABLE #Srs
(
column01 VARCHAR(100),
employee_number VARCHAR(10)
)
INSERT INTO #Srs
(column01,
employee_number)
VALUES ('1', '111'),
('2', '222'),
('3', '333'),
('4', '444');
WITH cteTable
AS (SELECT column01,
employee_number
FROM #Srs)
INSERT INTO #Target
(column01,
employee_number)
SELECT * from (Delete from cteTable output deleted.column01, deleted.employee_number) t
Does it have to be only one statement? If not you can use this.
begin transaction;
insert into Target(column01, employee_number)
select column01, employee_number
from Srs with (updlock, holdlock)
except
select column01, employee_number
from Target;
delete from Srs;
commit transaction;

Inserting records in loop without any unique columns

I have the following table for example which does not have any identity or unique column:
create table tbl_test ( first_name nvarchar(255), last_name nvarchar(255),
[address] nvarchar(255))
Insert tbl_test values ('Andrei','Corovei','str Meteor')
Insert tbl_test values ('Pop','Ionut','str Meteor')
Insert tbl_test values ('Whitehead','John','str Lunii')
Insert tbl_test values ('Grisham','Robert','str Corcoduselor')
Insert tbl_test values ('Eugen','Johnesco','str Prunelor')
I can insert the rows from the above table to a another table using below syntax:
select * into tbl_test_loop from tbl_test
This will insert all records in one shot.
Can I insert in a loop with a batch count of 2 the above results rather than at one shot without creating any Identity or rownumber function?
Declare #loopcount int
Declare #rcount int
Declare #idn int
Declare #iteration int
Declare #strsql varchar(1000)
select #loopcount=2,#idn=1
select #rcount=count(*) from tbl_test
SET #iteration=(#rcount/#loopcount)+(#rcount%#loopcount)
while(#idn<=#iteration)
BEGIN
SET #strsql='INSERT INTO tbl_test_loop select top '+cast(#loopcount as varchar(2))+' * from tbl_test t where not exists(select * from tbl_test_loop l where l.first_name = t.first_name and l.last_name = t.last_name and l.[address] = t.[address])'
exec(#strsql)
select 'inserted '+cast(#loopcount as varchar(2))
SET #idn=#idn+1
END
select tbl_test.* into tbl_test_loop from tbl_test, ( select 1 as loop union select 2) v
Try NTILE, no loop required:
select NTILE(3) OVER( ORDER BY ( SELECT 1 ) ) x, *
into tbl_test_loop
from tbl_test

Resources