I'm trying to insert some XML data from a XML column into a temp table in SQL Server 2012.
This is my current query
DECLARE #XML AS XML, #hDoc AS INT, #SQL NVARCHAR (MAX)
IF OBJECT_ID('tempdb..dbo.#txn','u') IS NOT NULL
BEGIN
PRINT '#temp exists! drop table'
DROP TABLE tempdb.dbo.#txn;
END
ELSE
BEGIN
PRINT '#temp does not exist! create table'
CREATE TABLE #txn
(
accountcode varchar(100),
tienda varchar(100),
caja varchar(100),
cajero varchar(100),
fecha varchar(100),
transaccion varchar(100),
itemcode varchar(100),
description varchar(100),
quantity numeric(10,3),
weight numeric(10,3),
qty_weight numeric(10,3),
unitprice numeric(15,3),
totalprice numeric(15,3),
vatcode varchar(100),
hashcode varchar(100),
anulado varchar(100)
)
END
SELECT #XML = [LoadedXML] FROM [dbo].[XmlImport]
EXEC sp_xml_preparedocument #hDoc OUTPUT, #XML
INSERT INTO #txn (accountcode, tienda, caja, cajero, fecha, transaccion, itemcode, description, quantity, weight, qty_weight, unitprice, totalprice, vatcode, hashcode, anulado)
SELECT
CASE
WHEN codigotienda = 1 THEN '01'
END as accountcode,
tienda,
caja,
cajero,
fecha,
transaccion,
itemcode,
description,
quantity,
weight,
CASE
WHEN quantity IS NULL THEN weight
WHEN weight IS NULL THEN quantity
END as qty_weight,
unitprice,
totalprice,
CASE
WHEN vatcode = 4 THEN 'V0'
WHEN vatcode = 1 THEN 'V1'
WHEN vatcode = 2 THEN 'V2'
WHEN vatcode = 3 THEN 'V3'
WHEN vatcode is NULL THEN 'V0'
END AS vatcode,
hashcode,
anulado
FROM
OPENXML(#hDoc, 'tcpos-export/transactions/transaction/trans-item')
WITH
(
codigotienda [varchar](100) '../shop/code',
tienda [varchar](100) '../shop/description',
caja [varchar](100) '../till/code',
cajero [varchar](100) '../cashier/code',
fecha [varchar](100) '../beginning-timestamp',
transaccion [varchar](100) '../trans-num',
itemcode [varchar](100) 'code',
description [varchar](100) 'description',
quantity numeric(10,3) 'quantity',
weight numeric(10,3) 'weight',
unitprice numeric(15,3) 'unit-price',
totalprice numeric(15,3) 'taxable-amount',
vatcode [varchar](100) 'vat-code',
hashcode [varchar](100) 'hash-code',
anulado [varchar](100) 'delete-operator-id'
)
SELECT *
FROM #txn
WHERE hashcode IS NOT NULL
AND totalprice NOT LIKE '%-%'
AND unitprice NOT LIKE '%-%'
AND anulado IS NULL
ORDER BY
CAST(hashcode AS int)
--LEFT JOIN [MAXIMERCADODEMO].[dbo].OITM sap
--ON #txn.itemcode = sap.itemcode COLLATE SQL_Latin1_General_CP1_CI_AS
--where #txn.itemcode is null
--SELECT #txn.itemcode FROM #txn
--LEFT JOIN [MAXIMERCADODEMO].[dbo].OITM sap
--ON #txn.itemcode = sap.itemcode COLLATE SQL_Latin1_General_CP1_CI_AS
--where #txn.itemcode is null
EXEC sp_xml_removedocument #hDoc
This works the first time. When I run it a second time, it should drop the temp table, but I get this error instead:
#temp does not exist! create table
Msg 2714, Level 16, State 6, Line 11
There is already an object named '#txn' in the database.
I don't know if you guys recommend me using a temp table or create a real table in my database to manage this situation?
This
IF OBJECT_ID('tempdb..#txn','u') IS NOT NULL
Should be
IF OBJECT_ID('tempdb..#txn', 'u') IS NOT NULL DROP TABLE #txn;
You could even get away with just:
IF OBJECT_ID('tempdb..#txn') IS NOT NULL
Once you make this change you no longer need the big IF statement checking for this.
Do yourself a favour and don't use that ancient XML procedure OPENXML. Instead use .nodes and .value
You can even use XQuery predicates instead of the WHERE clause
SELECT CASE
WHEN trans.value('(shop/code/text())[1]','varchar(100)') = '1' THEN '01'
END as accountcode,
trans.value('(shop/description/text())[1]','varchar(100)') tienda,
trans.value('(till/code/text())[1]','varchar(100)') caja,
trans.value('(cashier/code/text())[1]','varchar(100)') cajero,
trans.value('(beginning-timestamp/text())[1]','varchar(100)') fecha,
trans.value('(trans-num/text())[1]','varchar(100)') transaccion,
item.value('(code/text())[1]','varchar(100)') itemcode,
item.value('(description/text())[1]','varchar(100)') description,
v.quantity,
v.weight,
CASE
WHEN v.quantity is null THEN v.weight
WHEN v.weight is null THEN v.quantity
END as qty_weight,
item.value('(unit-price/text())[1]','numeric(15,3)') unitprice,
item.value('(taxable-amount/text())[1]','numeric(15,3)') totalprice,
CASE
WHEN vatcode = '4' THEN 'V0'
WHEN vatcode = '1' THEN 'V1'
WHEN vatcode = '2' THEN 'V2'
WHEN vatcode = '3' THEN 'V3'
WHEN vatcode is NULL THEN 'V0'
END AS vatcode,
item.value('(hash-code/text())[1]','int') hashcode,
item.value('(delete-operator-id/text())[1]','varchar(100)') anulado
FROM [dbo].[XmlImport] xi
CROSS APPLY xi.[LoadedXML].nodes('tcpos-export/transactions/transaction') x1(trans)
CROSS APPLY x1.trans.nodes('trans-item[
hash-code/text() and
not( unit-price[contains(text()[1], "-")] ) and
not( taxable-amount[contains(text()[1], "-")] ) and
not( delete-operator-id/text() )
]') x2(item)
CROSS APPLY (VALUES (
item.value('(quantity/text())[1]','numeric(10,3)'),
item.value('(weight/text())[1]','numeric(10,3)'),
item.value('(vat-code/text())[1]','varchar(100)')
) ) v(quantity, weight, vatcode)
ORDER BY hashcode;
Related
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
Table structure is as follows:
CREATE TABLE tblContact
(
SrNo DECIMAL IDENTITY(1,1) NOT NULL,
InquiryId VARCHAR(10) PRIMARY KEY,
SenderName VARCHAR(50),
SenderEmail VARCHAR(200),
SenderSubject VARCHAR(50),
SenderMessage VARCHAR(MAX),
IsActive BIT DEFAULT(1),
IsDelete BIT DEFAULT(0),
CreatedOn DATETIME DEFAULT(GETDATE()),
CreatedBy VARCHAR(10),
UpdatedOn DATETIME,
UpdatedBy VARCHAR(10)
)
Procedure listing is as follows:
CREATE PROC Usp_GetNewInquiryId
AS
BEGIN
IF NOT EXISTS(SELECT InquiryId FROM JobPortal.dbo.tblContact)
DECLARE #PrefixValue VARCHAR(10) = 'INQ'
DECLARE #InitialValue DECIMAL(10) = 1001
SELECT InquiryId = #PrefixValue + CAST(ISNULL(MAX(InquiryId), #InitialValue) AS VARCHAR(10))
FROM JobPortal.dbo.tblContact
ELSE
/* here I want to eliminate the word 'INQ' from 'INQ1001' towards left side and do increment 1002 from 1001, lastly want to select INQ1002 and so on... */
SELECT TOP 1
InquiryId = #PrefixValue + CONVERT(VARCHAR(10), SUBSTRING(InquiryId, 4, 4)) + 1
FROM JobPortal.dbo.tblContact
ORDER BY InquiryId DESC
END
Desired Output:
If table is empty then InquiryId=INQ1001
Otherwise InquiryId=INQ1002
If you want to return the "next available" InquiryId for tblContact, I would do this:
CREATE PROCEDURE Usp_GetNewInquiryId
AS
BEGIN
IF NOT EXISTS (SELECT InquiryId FROM tblContact)
SELECT 'INQ1001'
ELSE
SELECT TOP 1 'INQ' + CONVERT(VARCHAR,CONVERT(INT,REPLACE(InquiryId,'INQ','')) + 1) FROM tblContact ORDER BY InquiryId DESC
END
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.
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
In A Table Cityid and CITYname 2 Columns:
city id city name
1 Bang
1 hyd
1 pune
2 hyd
2 pune
2 chennai
I want the Result:
1 ---hyd,pune,bang(all citynames of city id)
2---
You left off some key details required to answer your question: What language are you using?
Here is the answer if you are using T-SQL on SQL Server 2005/2008:
Your Table:
CREATE TABLE [dbo].[cities](
[cityid] [int] NULL,
[cityname] [varchar](50) NULL
) ON [PRIMARY]
Your Data:
insert into cities(cityid,cityname)values(1,'Seattle')
insert into cities(cityid,cityname)values(1,'Portland')
insert into cities(cityid,cityname)values(2,'New York')
insert into cities(cityid,cityname)values(2,'Newark')
Your Query:
declare #result table(
cityid int,
cityname varchar(max)
)
declare #queue table(
cityid int,
cityname varchar(50)
)
declare #cityid int
declare #cityname varchar(50)
insert into #queue select * from cities
while(exists(select top 1 cityid from #queue)) begin
select top 1 #cityid = cityid, #cityname = cityname from #queue
if(exists(select cityid from #result where cityid = #cityid)) begin
update #result
set cityname = cityname + ', ' + #cityname
where cityid = #cityid
end else begin
insert into #result(cityid,cityname) values(#cityid,#cityname)
end
delete from #queue where cityid = #cityid and cityname = #cityname
end
select * from #result
Your Result:
cityid cityname
1 1 Seattle, Portland
2 2 New York, Newark
look up GROUP_CONCAT
or USER DEFINED AGGREGATE FUNCTIONS