Insert values into table with procedure - sql-server

I tried to implement procedure which main goal is to store data into separate table.I order to do this first I started with simple query with scalar variables. Below you can see code:
DECLARE #CustomerId int=8
DECLARE #validFrom date='2019.01.01'
DECLARE #ValidTo date='2019.03.01'
DECLARE #EmployeeID int=8
SELECT CONCAT(c.FirstName, ' ', c.LastName) AS CustomerFullName, lo.Name as LocationName,acd.Amount,cu.Name as Currency,acc.EmployeeId,#validFrom as ValidFrom,#ValidTo as ValidTo,CONCAT(emp.FirstName, ' ', emp.LastName) AS EmployeeFullName
FROM dbo.Customer as c
INNER JOIN dbo.Account AS acc ON acc.CurrencyId=c.Id
INNER JOIN dbo.AccountDetails AS acd ON acd.AccountId=acc.Id
INNER JOIN dbo.Currency AS cu ON cu.id=acc.CurrencyId
INNER JOIN dbo.Location as lo ON lo.Id=acd.LocationId
INNER JOIN dbo.Employee AS emp ON emp.ID=acc.EmployeeId
WHERE acc.CustomerId=#CustomerId and acd.TransactionDate between #validFrom and #ValidTo and acc.EmployeeId=#EmployeeID
So code above works great and give me expect results.
So next step is to put this code into procedure in order to filling table with data from procedure.For that reason I make table and also I try to put code above into procedure
CREATE TABLE dbo.CustomerReportLogs (
ID int IDENTITY (1,1) NOT NULL,
CustomerFullName NVARCHAR(100) NOT NULL,
LocationName NVARCHAR(100) NOT NULL,
Amount decimal (18,2) NOT NULL,
Currency NVARCHAR (20)NOT NULL,
EmployeeId int NOT NULL,
ValidFrom date NOT NULL,
ValidTo date NOT NULL,
EmployeeFullName NVARCHAR(100) NOT NULL,
CONSTRAINT PK_ID_CustomerReportLogs PRIMARY KEY CLUSTERED (
ID ASC
))
GO
CREATE OR ALTER PROCEDURE dbo.procedure1 (#CustomerId int, #validFrom date, #ValidTo date,#EmployeeID int)
AS
BEGIN
SELECT CONCAT(c.FirstName, ' ', c.LastName) AS CustomerFullName, lo.Name as LocationName,acd.Amount,cu.Name as Currency,acc.EmployeeId,#validFrom as ValidFrom,#ValidTo as ValidTo,CONCAT(emp.FirstName, ' ', emp.LastName) AS EmployeeFullName
FROM dbo.Customer as c
INNER JOIN dbo.Account AS acc ON acc.CurrencyId=c.Id
INNER JOIN dbo.AccountDetails AS acd ON acd.AccountId=acc.Id
INNER JOIN dbo.Currency AS cu ON cu.id=acc.CurrencyId
INNER JOIN dbo.Location as lo ON lo.Id=acd.LocationId
INNER JOIN dbo.Employee AS emp ON emp.ID=acc.EmployeeId
WHERE acc.CustomerId=#CustomerId and acd.TransactionDate between #validFrom and #ValidTo and acc.EmployeeId=#EmployeeID
SELECT *
INSERT INTO dbo.CustomerReportLogs(CustomerFullName,LocationName,Amount,Currency,EmployeeId,ValidFrom,ValidTo,EmployeeFullName)
VALUES (#CustomerFullName,#LocationName,#Amount,#Currency,#EmployeeId,#ValidFrom,#ValidTo,#EmployeeFullName)
Return
END
GO
Error message from above procedure is that I need to declare scalar variable #CustomerFullName,but this variable actually I got from code with concat function and is not scalar. So probably in last part of my code I have some errors. So can anybody help me how to fix this errors?
Msg 137, Level 15, State 2, Procedure procedure1, Line 29 [Batch Start Line 3767]
Must declare the scalar variable "#CustomerFullName".

You aren't actually storing your returned values in variables. You could do that I.e. you first declare the variables and then use something like SELECT #CustomerFullName = CONCAT(c.FirstName, ' ', c.LastName) .... FROM ... , but far easier would be to replace your SELECT directly with the INSERT. I.e.
CREATE OR ALTER PROCEDURE dbo.procedure1 (#CustomerId int, #validFrom date, #ValidTo date,#EmployeeID int)
AS
BEGIN
INSERT INTO dbo.CustomerReportLogs(
CustomerFullName
, LocationName
, Amount
, Currency
, EmployeeId
, ValidFrom
, ValidTo
, EmployeeFullName
)
SELECT
CONCAT(c.FirstName, ' ', c.LastName) AS CustomerFullName
, lo.Name as LocationName
, acd.Amount
, cu.Name as Currency
, acc.EmployeeId
, #validFrom as ValidFrom
, #ValidTo as ValidTo
, CONCAT(emp.FirstName, ' ', emp.LastName) AS EmployeeFullName
FROM
dbo.Customer as c
INNER JOIN dbo.Account AS acc ON acc.CurrencyId=c.Id
INNER JOIN dbo.AccountDetails AS acd ON acd.AccountId=acc.Id
INNER JOIN dbo.Currency AS cu ON cu.id=acc.CurrencyId
INNER JOIN dbo.Location as lo ON lo.Id=acd.LocationId
INNER JOIN dbo.Employee AS emp ON emp.ID=acc.EmployeeId
WHERE
acc.CustomerId = #CustomerId
AND acd.TransactionDate BETWEEN #validFrom AND #ValidTo
AND acc.EmployeeId = #EmployeeID
END
Please note this has not been tested, but I just copy/pasted your own code

Related

Update table with stored procedure without null

I tried to implement procedure which main goal is to store data into new separate table.First I create table which I want to populate with data
CREATE TABLE dbo.CustomerReportLogs (
ID int IDENTITY (1,1) NOT NULL,
CustomerFullName NVARCHAR(100) NULL,
LocationName NVARCHAR(100) NULL,
Amount decimal (18,2) NULL,
Currency NVARCHAR (20) NULL,
EmployeeId int NULL,
ValidFrom date NULL,
ValidTo date NULL,
CONSTRAINT PK_ID_CustomerReportLogs PRIMARY KEY CLUSTERED (
ID ASC
))
GO
So next step is how to populate this table with stored procedure. I order to do this I wrote this lines of code:
CREATE OR ALTER PROCEDURE dbo.procedure2 (#CustomerId int, #validFrom date, #ValidTo date,#EmployeeID int)
AS
BEGIN
SELECT CONCAT(c.FirstName, ' ', c.LastName) AS CustomerFullName, lo.Name as LocationName,acd.Amount as Amount,cu.Name as Currency,acc.EmployeeId,#validFrom as ValidFrom,#ValidTo as ValidTo
FROM dbo.Customer as c
INNER JOIN dbo.Account AS acc ON acc.CurrencyId=c.Id
INNER JOIN dbo.AccountDetails AS acd ON acd.AccountId=acc.Id
INNER JOIN dbo.Currency AS cu ON cu.id=acc.CurrencyId
INNER JOIN dbo.Location as lo ON lo.Id=acd.LocationId
INNER JOIN dbo.Employee AS emp ON emp.ID=acc.EmployeeId
WHERE acc.CustomerId=#CustomerId and acd.TransactionDate between #validFrom and #ValidTo and acc.EmployeeId=#EmployeeID
DECLARE #CustomerFullName NVARCHAR(100)
DECLARE #LocationName NVARCHAR(100)
DECLARE #Amount decimal (18,2)
DECLARE #Currency NVARCHAR (20)
INSERT INTO dbo.CustomerReportLogs(CustomerFullName,LocationName,Amount,Currency,EmployeeId,ValidFrom,ValidTo)
VALUES (#CustomerFullName,#LocationName,#Amount,#Currency,#EmployeeId,#ValidFrom,#ValidTo)
SELECT #CustomerFullName as CustomerFullName,#LocationName AS LocationName,#Amount AS Amount,#Currency as Currency,
#EmployeeId as EmployeeId,#ValidFrom as ValidFrom ,#ValidTo as ValidTo
END
GO
Above line code create stored procudure but now new problem arise namely when I try to execute first whit this command
EXEC dbo.procedure2 #CustomerId=8,#validFrom='2019.01.25', #ValidTo='2019.03.01', #EmployeeID=8
So this procedure can't update properly dbo.CustomerReportLogs so I got some results with null and some with values.Output you can see on pic below:
[![enter image description here][1]][1]
So can anybody help me how to update this table properly not with null
CREATE OR ALTER PROCEDURE dbo.procedure2 (
#CustomerId INT
,#validFrom DATE
,#ValidTo DATE
,#EmployeeID INT
)
AS
BEGIN
INSERT INTO dbo.CustomerReportLogs (
CustomerFullName
,LocationName
,Amount
,Currency
,EmployeeId
,ValidFrom
,ValidTo
)
OUTPUT INSERTED.[CustomerFullName],INSERTED.[LocationName],INSERTED.[Amount],INSERTED.[Currency],INSERTED.[EmployeeId],INSERTED.[ValidFrom] ,INSERTED.[ValidTo]
SELECT CONCAT (c.FirstName,' ',c.LastName) AS CustomerFullName
,lo.Name AS LocationName
,acd.Amount AS Amount
,cu.Name AS Currency
,acc.EmployeeId
,#validFrom AS ValidFrom
,#ValidTo AS ValidTo
FROM dbo.Customer AS c
INNER JOIN dbo.Account AS acc ON acc.CurrencyId = c.Id
INNER JOIN dbo.AccountDetails AS acd ON acd.AccountId = acc.Id
INNER JOIN dbo.Currency AS cu ON cu.id = acc.CurrencyId
INNER JOIN dbo.Location AS lo ON lo.Id = acd.LocationId
INNER JOIN dbo.Employee AS emp ON emp.ID = acc.EmployeeId
WHERE acc.CustomerId = #CustomerId
AND acd.TransactionDate BETWEEN #validFrom
AND #ValidTo
AND acc.EmployeeId = #EmployeeID
END

Why UNION used in a stored procedure in derived table?

I am not author of the stored procedure and I am wondering why they used UNION in SELECT statement when selecting from the derived table ...
If I comment out the whole UNION ALL SELECT statement, I get the same result with the same basically performance.
So I am just wonder why it is there? What kind of trick does it makes?
Below is the whole stored procedure in case I am missing something
ALTER PROCEDURE [dbo].[rptActivityLog] --'1/1/2016', '2/3/2016'
(#DateFrom datetime = null,
#DateTo datetime = null,
#UserGuid uniqueidentifier = null,
#CurrentUserGuid uniqueidentifier = NULL)
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DECLARE #UserID SMALLINT
SELECT #UserID = UserID
FROM tblUsers
WHERE (UserGUID = #UserGuid)
DECLARE #ValidOfficeGuids TABLE (OfficeGuid uniqueidentifier primary key)
--if user is in tblUserQuotingOffice then use only that Office
--otherwise they will have access to all offices
IF EXISTS (SELECT OfficeGuid
FROM tblUserQuotingOffice
WHERE UserGuid = #CurrentUserGuid)
BEGIN
INSERT INTO #ValidOfficeGuids
SELECT OfficeGuid
FROM tblUserQuotingOffice
WHERE UserGuid = #CurrentUserGuid
END
ELSE
BEGIN
INSERT INTO #ValidOfficeGuids
SELECT OfficeGUID
FROM tblClientOffices
END
DECLARE #compareDateFrom DATETIME
set #compareDateFrom = CAST(CONVERT(VARCHAR(50), #DateFrom, 101) AS DATETIME)
declare #compareDateTo datetime
set #compareDateTo = DateAdd(ms, -2, DateAdd(d, 1, CAST(CONVERT(VARCHAR(50), DATEADD(day, 7, #DateTo), 101) AS DATETIME)))
--First get the log entries
declare #logResults table
(
ID int primary key not null
, IdentifierGuid uniqueidentifier
)
insert into #logResults
select
l.ID
, l.IndentifierGuid
from
tblLog l
where
l.ActionDate between #compareDateFrom and #compareDateTo
and l.IndentifierGuid is not null
select
distinct
T.UserName
, T.ControlNo
, T.InsuredPolicyName
, Replace(Replace(T.[Action],Char(10),''),Char(13),'') as [Action]
, T.ActionDate
, T.LineName as LOB
from
(
select
u.UserName
, q.ControlNo
, q.InsuredPolicyName
, l.[Action]
, l.ActionDate
, ll.LineName
, l.UserID
from
#logResults r
inner join tblLog l on r.ID = l.ID
inner join tblUsers u on l.UserID = u.UserID
inner join tblQuotes q on r.IdentifierGuid = q.QuoteGUID
inner join lstLines ll on q.LineGUID = ll.LineGUID
-- WHY DO WE USE BELOW UNION STATEMENT??????????????????????????????????
union
select
u.UserName
, q.ControlNo
, q.InsuredPolicyName
, l.[Action]
, l.ActionDate
, ll.LineName
, l.UserID
from
#logResults r
inner join tblLog l on r.ID = l.ID
inner join tblUsers u on l.UserID = u.UserID
inner join tblQuotes q on r.IdentifierGuid = q.ControlGUID
inner join lstLines ll on q.LineGUID = ll.LineGUID
) T
WHERE IsNull(#UserID, T.UserID) = T.UserID
order by
T.ActionDate
There is a difference in the join with tblQuotes, looks like the union is meant to union two different datasets (one for QuoteGUIDs and one for ControlGUIDs)

but give me error that invalid object name #temp2

Alter procedure spMRI_TAG_try
#DocNum int
as
declare #cnt int
declare #count int
declare #cardname nvarchar(100)
declare #Docdate datetime
declare #itemCode nvarchar(50)
declare #Dscription nvarchar(100)
declare #Quantity numeric(19,6)
declare #ManBtchNum char(1)
declare #SalPackUn numeric(19,6)
declare #ExpDate datetime
begin
set #cnt = 1
select #Count = pdn1.Quantity/OITM.SalPackUn from pdn1 inner join OITM on pdn1.ItemCode=OITM.ItemCode
while #cnt <= #count
insert into #temp2 values(#cardname,#DocDate,#itemcode,#Dscription,#Quantity,#ManBtchNum,#SalPackUn,#ExpDate)
select #cardname = a.CardName,#DocDate=a.DocDate,#itemcode=b.ItemCode,#Dscription=b.Dscription,#Quantity=b.Quantity,#ManBtchNum=c.ManBtchNum,#SalPackUn=c.SalPackUn,#ExpDate=d.ExpDate
from OPDN a inner join PDN1 b on a.DocEntry = b.DocEntry inner join OITM c on c.ItemCode = b.ItemCode inner join OBTN d on c.ItemCode = d.ItemCode and a.DocNum=#DocNum and d.ExpDate is not null
set #cnt=#cnt+1
end
select * from #temp2
but gives me an invalid object name #temp2 error.
Create temp table before your while loop:
create table #temp2 (Cardname ...)
while #cnt <= #count
insert into #temp2 values(#cardname,#DocDate,#itemcode,#Dscription,#Quantity,#ManBtchNum,#SalPackUn,#ExpDate)
select #cardname = a.CardName,#DocDate=a.DocDate,#itemcode=b.ItemCode,#Dscription=b.Dscription,#Quantity=b.Quantity,#ManBtchNum=c.ManBtchNum,#SalPackUn=c.SalPackUn,#ExpDate=d.ExpDate
Two points here:
Not sure why you are using looping - Try set based approaches. You can solve most of the problems in set based queries
You can create temp tables using select * into #temp2... Check for that syntax in msdn
To be honest your SP is a one big messed up code :)
I suggest you to rewrite it like this:
ALTER PROCEDURE spMRI_TAG_try
#DocNum int
AS
--Drop table if it exists
IF OBJECT_ID(N'#temp2') IS NOT NULL DROP TABLE #temp2
--create table
CREATE TABLE #temp2 (
cardname nvarchar(100),
Docdate datetime,
itemCode nvarchar(50),
Dscription nvarchar(100),
Quantity numeric(19,6),
ManBtchNum char(1),
SalPackUn numeric(19,6),
ExpDate datetime
)
--Make the insertion
INSERT INTO #temp2
SELECT a.CardName,
a.DocDate,
b.ItemCode,
b.Dscription,
b.Quantity,
c.ManBtchNum,
c.SalPackUn,
d.ExpDate
FROM OPDN a
INNER JOIN PDN1 b
ON a.DocEntry = b.DocEntry
INNER JOIN OITM c
ON c.ItemCode = b.ItemCode
INNER JOIN OBTN d
ON c.ItemCode = d.ItemCode and a.DocNum=#DocNum and d.ExpDate is not null
--output
SELECT *
FROM #temp2
No need a while loop (I can not even understand how you will switch through the rows, in your solution it will write the same row the '#count' times), you can write all data directly in temp table.
You get error because of there is no #temp2 table on the moment you are trying to insert, also there is no checking if the table already exists.
As was noted in answer by Kannan Kandasamy, the one more way is to use SELECT * INTO #temp2, it can be achieved this way:
ALTER PROCEDURE spMRI_TAG_try
#DocNum int
AS
IF OBJECT_ID(N'#temp2') IS NOT NULL DROP TABLE #temp2
SELECT a.CardName,
a.DocDate,
b.ItemCode,
b.Dscription,
b.Quantity,
c.ManBtchNum,
c.SalPackUn,
d.ExpDate
INTO #temp2
FROM OPDN a
INNER JOIN PDN1 b
ON a.DocEntry = b.DocEntry
INNER JOIN OITM c
ON c.ItemCode = b.ItemCode
INNER JOIN OBTN d
ON c.ItemCode = d.ItemCode and a.DocNum=#DocNum and d.ExpDate is not null
SELECT *
FROM #temp2

SQL query stored procedure

Create a stored procedure that passes in the SalesOrderID as a parameter.
This stored procedure will return the SalesOrderID, Date of the transaction, shipping date, city and state. It is not running
Ans:
Create PROCEDURE proc_findProductInfo
#SalesOrderID int,
#SalesOrderOut int OUTPUT,
#OrderDate datetime OUTPUT,
#ShipDate datetime OUTPUT,
#CityState varchar(100) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #SalesOrderOut = #SalesOrderID
SET #OrderDate = (SELECT OrderDate FROM SALES.SalesOrderHeader )
SET #ShipDate = (SELECT ShipDate FROM Sales.SalesOrderHeader)
SET #CityState = (SELECT a.City, st.Name
FROM Sales.SalesOrderHeader s
INNER JOIN Person.Address a ON s.ShipToAddressID = a.AddressID
INNER JOIN Person.StateProvince st ON s.TerritoryID = st.TerritoryID
WHERE SalesOrderID = #SalesOrderID)
END
DECLARE #OrderNum int, #Date datetime, #qty1 int, #Date1 datetime
EXEC proc_findProductInfo 63936,
#SalesOrderOut = #OrderNum OUTPUT,
#OrderDate = #Date OUTPUT,
#ShipDate = #date1,
#CityState = #qty1 output
SELECT #OrderNum, #date, #qty1, #Date1
Error Message:
Msg 116, Level 16, State 1, Procedure proc_findProductInfo, Line 25
Only one expression can be specified in the select list when the
subquery is not introduced with EXISTS
You're making this way harder than it needs to be:
Create PROCEDURE proc_findProductInfo
#SalesOrderID int
AS
BEGIN
SET NOCOUNT ON;
SELECT s.SalesOrderID, s.OrderDate, s.ShipDate, a.City,st.Name
FROM Sales.SalesOrderHeader s
INNER JOIN Person.Address a ON s.ShipToAddressID = a.AddressID
INNER JOIN Person.StateProvince st ON s.TerritoryID=st.TerritoryID
WHERE s.SalesOrderID = #SalesOrderID
END
I'm not even sure you need the StateProvince table here... the question probably allows you to trust the Address record.
It is complaining about the following
SET #CityState = (
SELECT a.City,st.Name
You are selecting both City and State Name and trying to assign it to a variable.
You either need to concatenate or coalesce them into them into a single output or alternatively use the below type of select to assign each one to a variable.
select
#var1 = field1,
#var2 = field2,
...
As below
SET #SalesOrderOut = #SalesOrderID
SELECT #OrderDate = s.OrderDate,
#ShipDate = s.ShipDate,
#CityState = CONCAT(a.City, ", ", st.Name)
FROM Sales.SalesOrderHeader s
inner JOIN Person.Address a
ON s.ShipToAddressID = a.AddressID
inner JOIN Person.StateProvince st
on s.TerritoryID=st.TerritoryID
WHERE SalesOrderID = #SalesOrderID

Column name or number of supplied values does not match table definition in stored procedure

I added a new line like this:
#imageunc + 'signatures\' + RTRIM(salespoc.SLPRSNFN) + ' '
+ RTRIM(salespoc.SPRSNSLN) + '.jpg' AS 'SigImagePath'
Then started receiving an error:
"Msg 213, Level 16, State 1, Procedure MVTS_repContractQuote, Line 58
Column name or number of supplied values does not match table definition."
Below is my stored procedure.
Can someone help me on this?
USE [TEST]
GO
/****** Object: StoredProcedure [dbo].[TEST_repContractQuote] Script Date: 09/08/2014 10:48:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
exec TEST_repContractQuote '0000000023 '
exec TEST_repContractQuote '1000000045 '
select STRTDATE, ENDDATE, CONFGREF, * from svc00601 where contnbr='1000000045'
*/
ALTER procedure [dbo].[MVTS_repContractQuote] #ContractNo AS VARCHAR(20) AS
BEGIN
DECLARE #rep TABLE (
CustNo VARCHAR(20),
CustName VARCHAR(200),
Addr1 VARCHAR(100),
Addr2 VARCHAR(100),
Addr3 VARCHAR(100),
CSZ VARCHAR(100),
Country VARCHAR(50),
ContactPerson VARCHAR(50),
Phone VARCHAR(20),
Fax VARCHAR(20),
Qty NUMERIC(9,2),
Desc1 VARCHAR(200),
Desc2 VARCHAR(200),
StartDate DATETIME,
EndDate DATETIME,
Desc3 VARCHAR(200),
LineNoteindx NUMERIC(19,5),
LineNotes TEXT,
LineTotal NUMERIC(12,2),
Total NUMERIC(12,2),
CurrSymbol VARCHAR(5),
TermsOfSale VARCHAR(100),
PaymentTerms VARCHAR(200),
Warranty VARCHAR(100),
QuoteValidFor VARCHAR(100),
SalesPerson VARCHAR(200),
ContStatus SMALLINT,
Noteindx NUMERIC(19,5),
Notes TEXT)
-- Get the name of a random images in the d:\gpshare\images directory
declare #cmd varchar(255),
#rc int,
#imagepath varchar(1024),
#imagedir varchar(255),
#imageunc varchar(255)
select #imagedir = 'D:\gpshare\images\'
select #imageunc = '\\dynamics\gpshare\images\'
select #cmd = 'dir /b/a-d-h ' + #imagedir
declare #output table (output varchar(255) null)
insert #output exec #rc = master..xp_cmdshell #cmd
select #imagepath = (select TOP 1 #imageunc+output from #output where output is not null ORDER BY NEWID())
INSERT #rep
SELECT h.CUSTNMBR,
cust.CUSTNAME AS 'CustomerName',
adr.ADDRESS1,
adr.ADDRESS2,
adr.ADDRESS3,
RTRIM(adr.CITY)+', '+RTRIM(adr.STATE)+' '+RTRIM(adr.ZIP) AS CSZ, RTRIM(adr.COUNTRY) AS 'Country',
adr.CNTCPRSN,
'('+SUBSTRING(adr.PHONE1,1,3)+') '+SUBSTRING(adr.PHONE1,4,3)+'-'+SUBSTRING(adr.PHONE1,7,4) AS 'Phone',
CASE adr.FAX
WHEN '' THEN ''
ELSE '('+SUBSTRING(adr.FAX,1,3)+') '+SUBSTRING(adr.FAX,4,3)+'-'+SUBSTRING(adr.FAX,7,4) END AS 'FaxNo',
MAX(l.QUANTITY) AS 'Qty',
(SELECT TOP 1 sl.DSCRIPTN FROM SVC00601 sl
WHERE sl.CONTNBR=#ContractNo AND sl.CONSTS=l.CONSTS AND sl.LNSEQNBR=MIN(l.LNSEQNBR)) AS 'Desc1',
(SELECT TOP 1 sl.SERLNMBR FROM SVC00601 sl
WHERE sl.CONTNBR=#ContractNo AND sl.CONSTS=l.CONSTS AND sl.LNSEQNBR=MIN(l.LNSEQNBR)) AS 'Desc2',
(SELECT TOP 1 sl.STRTDATE FROM SVC00601 sl
WHERE sl.CONTNBR=#ContractNo AND sl.CONSTS=l.CONSTS AND sl.LNSEQNBR=MIN(l.LNSEQNBR)) AS 'StartDate',
(SELECT TOP 1 sl.ENDDATE FROM SVC00601 sl
WHERE sl.CONTNBR=#ContractNo AND sl.CONSTS=l.CONSTS AND sl.LNSEQNBR=MIN(l.LNSEQNBR)) AS 'EndDate',
--MAX('Coverage Period: '+CAST(CAST(l.STRTDATE AS DATE) AS VARCHAR(20))+' - '+
--CAST(CAST(l.ENDDATE AS DATE) AS VARCHAR(20))) AS 'Desc3',
'' AS 'Desc3',
(SELECT TOP 1 sn.NOTEINDX FROM SVC00601 sl
JOIN SY03900 sn ON sn.NOTEINDX=sl.NOTEINDX
WHERE sl.CONTNBR=#ContractNo AND sl.CONSTS=l.CONSTS AND sl.LNSEQNBR=MIN(l.LNSEQNBR))
AS 'LineNoteIndx',
'',
SUM(l.ORIGTOTAL) AS 'LineTotal',
MAX(h.ORIGTOTAL) AS 'Total',
RTRIM(curr.CRNCYSYM) AS 'CurrSymbol',
RTRIM(e4F1.LONGNAME) AS 'TermsOfSale',
RTRIM(e4F2.LONGNAME) AS 'PaymentTerms',
RTRIM(e4F3.LONGNAME) AS 'Warranty',
RTRIM(e4F4.LONGNAME) AS 'QuoteValidFor',
RTRIM(salespoc.SLPRSNFN) + ' ' + RTRIM(salespoc.SPRSNSLN) AS 'SalesPerson',
#imageunc + 'signatures\' + RTRIM(salespoc.SLPRSNFN) + ' ' + RTRIM(salespoc.SPRSNSLN) + '.jpg' AS 'SigImagePath',
h.CONSTS,
h.NOTEINDX,
''
FROM svc00600 h
LEFT JOIN RM00102 adr ON RTRIM(h.CUSTNMBR)=RTRIM(adr.custnmbr) AND h.ADRSCODE=adr.ADRSCODE
LEFT JOIN RM00101 cust ON RTRIM(cust.CUSTNMBR) = RTRIM(adr.CUSTNMBR)
INNER JOIN DYNAMICS..MC40200 curr ON curr.CURNCYID=h.CURNCYID
INNER JOIN SVC00601 l ON RTRIM(h.CONTNBR)=RTRIM(l.CONTNBR) AND h.CONSTS=l.consts
LEFT JOIN EXT00103 e103F1 ON e103F1.PT_UD_Key=h.CONTNBR AND e103F1.PT_UD_Number=1 AND e103F1.PT_Window_ID='CONTRACTINFO'
LEFT JOIN EXT40102 e4F1 ON e4F1.PT_Window_ID=e103F1.PT_Window_ID AND e4F1.Field_Number=1 AND e4F1.lnitmseq=e103F1.total
LEFT JOIN EXT00103 e103F2 ON e103F2.PT_UD_Key=h.CONTNBR AND e103F2.PT_UD_Number=2 AND e103F2.PT_Window_ID='CONTRACTINFO'
LEFT JOIN EXT40102 e4F2 ON e4F2.PT_Window_ID=e103F2.PT_Window_ID AND e4F2.Field_Number=2 AND e4F2.lnitmseq=e103F2.total
LEFT JOIN EXT00103 e103F3 ON e103F3.PT_UD_Key=h.CONTNBR AND e103F3.PT_UD_Number=3 AND e103F3.PT_Window_ID='CONTRACTINFO'
LEFT JOIN EXT40102 e4F3 ON e4F3.PT_Window_ID=e103F3.PT_Window_ID AND e4F3.Field_Number=3 AND e4F3.lnitmseq=e103F3.total
LEFT JOIN EXT00103 e103F4 ON e103F4.PT_UD_Key=h.CONTNBR AND e103F4.PT_UD_Number=4 AND e103F4.PT_Window_ID='CONTRACTINFO'
LEFT JOIN RM00301 salespoc ON salespoc.SLPRSNID = h.SLPRSNID
LEFT JOIN EXT40102 e4F4 ON e4F4.PT_Window_ID=e103F4.PT_Window_ID AND e4F4.Field_Number=4 AND e4F4.lnitmseq=e103F4.total
WHERE RTRIM(h.CONTNBR)=RTRIM(#ContractNo)
AND (l.CONSTS=1 OR l.CONSTS=2)
GROUP BY l.CONFGREF, h.CUSTNMBR, cust.CUSTNAME, adr.ADDRESS1, adr.ADDRESS2, adr.ADDRESS3, adr.CITY, adr.STATE, adr.ZIP, adr.COUNTRY, adr.CNTCPRSN, adr.PHONE1, adr.FAX, h.CONTNBR, l.CONSTS,
curr.CRNCYSYM, e4F1.LONGNAME, e4F2.LONGNAME, e4F3.LONGNAME, e4F4.LONGNAME, salespoc.SLPRSNFN, salespoc.SPRSNSLN, h.CONSTS, h.NOTEINDX
HAVING h.CONSTS=(SELECT MAX(CONSTS) FROM SVC00600 WHERE CONTNBR=RTRIM(#ContractNo))
ORDER BY min(l.LNSEQNBR) ASC
UPDATE r
SET Notes=ISNULL((SELECT TXTFIELD FROM SY03900 WHERE NOTEINDX=r.Noteindx),''),
LineNotes=ISNULL((SELECT TXTFIELD FROM SY03900 WHERE NOTEINDX=r.LineNoteindx),''),
Desc3='Coverage Period: '+CAST(CAST(StartDate AS DATE) AS VARCHAR(20))+' - '+CAST(CAST(EndDate AS DATE) AS VARCHAR(20))
FROM #rep r
--SELECT * FROM #rep
SELECT *, convert(int,rand()*3)+1 as rnd from #rep
END
Your Query is pretty long and complex to quickly understand, but from what I can see your table has 29 fields and in you INSERT query you only set 21. That's not allowed on SQL without specify the fields names to be updated or inserted. For instance if you have a table with 3 columns like this:
Code
Desc
Qty
You can't use this:
INSERT INTO myTable SELECT 'myCode' as Code, 'myDesc' as Desc
Because you are missing the Qty field. Never the less, if the field Qty is nulleable, you can do this:
INSERT INTO myTable(Code, Desc) SELECT 'myCode' as Code, 'myDesc' as Desc
Hope this helps you.

Resources