Puzzling xml select syntax in Sql Server - sql-server

In the below sql code, what does T(C) mean? What is T and what is C?
declare #employeeData xml --this would be your XML input parameter
set #employeeData = '<employeeData>
<employee LastName="Smith" FirstName="Randolph" EmployeeID="1234567"/>
</employeeData>'
declare #xmlTable table (LastName nvarchar(255), FirstName nvarchar(255), EmployeeID int)
insert into #xmlTable (LastName, FirstName, EmployeeID)
select
C.value('#LastName','nvarchar(255)') as LastName,
C.value('#FirstName','nvarchar(255)') as FirstName,
C.value('#EmployeeID','int') as EmployeeID
from
#employeeData.nodes('/employeeData/employee') T(C)
select * from #xmlTable

Check MSDN: http://msdn.microsoft.com/en-us/library/ms188282.aspx
T - Table
C - Column

Related

Reading non latin character from XML variable and inserting into table

I am trying to insert some information in Arabic from a XML variable into a SQL Server table.
I did something like the below. However it does not work. Could you please tell what is missing?
Create Table EmployeeTbl
(
firstname nvarchar(100),
familyName nvarchar(100)
)
Insert into EmployeeTbl (firstName, FamilyName)
select
t.x.value('(./firstname)[1]', 'nvarchar(100)') as firstname,
t.x.value('(./familyname)[1]', 'nvarchar(100)') as familyname
from
#XMLVariable.nodes('//employeexml) t(x)
Yes, You missed a single-quotes(') at last line:
Create Table EmployeeTbl
(
firstname nvarchar(100),
familyName nvarchar(100)
)
Insert into EmployeeTbl (firstName, FamilyName)
select
t.x.value('(./firstname)[1]', 'nvarchar(100)') as firstname,
t.x.value('(./familyname)[1]', 'nvarchar(100)') as familyname
from
#XMLVariable.nodes('//employeexml') t(x)
Your XML file should be like that :
<employeexml Id="1">
<firstname>بشیر</firstname>
<familyname>المنادی</familyname>
</employeexml>
<employeexml Id="2">
<firstname>یعغوب</firstname>
<familyname>سمیر</familyname>
</employeexml>

Need comma separated value in table in SQL Server 2014 [duplicate]

This question already has answers here:
get a comma delimited string from rows [duplicate]
(2 answers)
Closed 4 years ago.
I have a table like this.
Create table #temp
(
id int,
firstname varchar(50),
lastname varchar(50)
)
insert into #temp (id, firstname, lastname)
select 1,'mit','jain'
insert into #temp (id, firstname, lastname)
select 1,'mit','jain1'
insert into #temp (id, firstname, lastname)
select 1,'mit','jain2'
insert into #temp (id, firstname, lastname)
select 2,'mit','jain3'
insert into #temp (id, firstname, lastname)
select 2,'mit','jain4'
insert into #temp (id, firstname, lastname)
select 1,'mit','jain5'
insert into #temp (id, firstname, lastname)
select 1,'mit','jain6'
I want the table to be shown as below
id firstname lastname
----------------------------------------------
1 mit jain,jain1,jain2,jain5,jain6
2 mit jain2,jain4
I have tried the query as below
select
id, firstname,
substring((Select ', '+tc1.lastname AS [text()]
From #temp tc1
Inner Join #temp c1 On c1.id = tc1.id
Where tc1.firstname = c1.firstname
Order BY tc1.lastname
For Xml Path('')), 2, 1000) 'LastName1'
from #temp
group by id, firstname
But it's not working. Please help me out
You're part of the way there. The tradition method is using STUFF:
SELECT t.id, t.firstname,
STUFF((SELECT ', ' + sq.lastname
FROM #temp sq
WHERE sq.id = t.id
AND sq.firstname = t.firstname
ORDER BY sq.lastname
FOR XML PATH('')),1,1,'') AS lastname
FROM #temp t
GROUP BY t.id, t.firstname;
There are lots of answers on SO already on how to do this though, but you have shown effort. :)

insert row by row data in table via openxml stored procedure in MS SQL

I m trying to insert the data VIA XML Format. And same the XML format defined as below & i wants to insert the field row by row in SQL Table. But, none of address is inserting in SQL Table, ONLY Customer information is inserting in Dummy Table.
<XML>
<Customer>
<NAME>YOGESH</NAME>
<CONTACT>YOGESH SHARMA</CONTACT>
<Mobile>123456789</Mobile>
<Status>A</Status>
<MALE>1</MALE>
<Add>
<ADD1>
<Address>AHMEDABAD</Address>
<State>GUJARAT</State>
<City>AHMEDABAD</City>
<Pincode>380016</Pincode>
</ADD1>
<ADD2>
<Address>RAJKOT</Address>
<State>GUJARAT</State>
<City>RAJKOT</City>
<Pincode>360001</Pincode>
</ADD2>
</Add>
</Customer>
</XML>
MY SP AS BELOW :
ALTER PROCEDURE [dbo].[OPENXMLDUMMY]
#xmlCustomer NTEXT
AS
BEGIN
DECLARE #DOC INT;
EXEC sp_xml_preparedocument
#DOC OUTPUT,
#xmlCustomer;
INSERT INTO Dummy
(Name,
Contact,
Mobile,
Status,
Male,
InsertDate
)
SELECT XML.NAME,
XML.Contact,
XML.Mobile,
XML.Status,
XML.Male,
GETDATE()
FROM OPENXML(#DOC, '/XML/Customer', 2) WITH(Name VARCHAR(50),
Contact VARCHAR(75), Mobile BIGINT, Status VARCHAR(10), Male VARCHAR(10),
InsertDate DATETIME) XML;
INSERT INTO DummyExtd
(
ID,
Address,
State,
City,
Pincode
) SELECT (SELECT ID FROM DUMMY WHERE Name = Name),
XML.Address,
XML.State,
XML.City,
XML.Pincode
FROM OPENXML(#DOC, '/XML/Customer/Add',2) WITH (ID INT, Address
VARCHAR(50), State VARCHAR(50), City VARCHAR(50), Pincode INT) XML;
EXEC sp_xml_removedocument #DOC;
END;
So, i just want to insert the data as below format in SQL Tables:
ID Name Contact Mobile Status Male InsertDate
1 YOGESH YOGESH SHARMA 123456789 A 1 2017-07-26 13:28:30.957
ID Address State City Pincode
1 AHMEDABAD GUJARAT AHMEDABAD 380016
1 RAJKOT GUJARAT RAJKOT 360001
So, what is the issue in my current stored procedure & needs to correct it.
Thanking you
Yogesh
Here I made one demo for the same. Please look into this.
Firstly, I created two tables which are Customer(your table name Dummy) and Customer_Address(your table name DummyText). They are look like below snaps.
Table : Customer
Table : Customer_Address
Below is your updated store procedure.
ALTER PROCEDURE [dbo].[OPENXMLDUMMY]
#xmlCustomer NTEXT
AS
BEGIN
DECLARE #DOC INT;
Declare #CustId INT;
EXEC sp_xml_preparedocument
#DOC OUTPUT,
#xmlCustomer;
INSERT INTO Customer(Name, Contact, Mobile, Status, Male, InsertDate)
SELECT XML.[NAME], XML.Contact, XML.Mobile, XML.Status, XML.Male, GETDATE() AS InsertDate
FROM OPENXML(#DOC, '/XML/Customer', 2) WITH(NAME VARCHAR(50), CONTACT VARCHAR(75), Mobile BIGINT, Status VARCHAR(10), MALE VARCHAR(10), InsertDate DATETIME) XML;
SET #CustId = SCOPE_IDENTITY()
INSERT INTO Customer_Address(Cust_Id, Address, State, City, Pincode)
SELECT #CustId AS Cust_Id, XML.Address, XML.State, XML.City, XML.Pincode
FROM OPENXML(#DOC, '/XML/Customer/Add/ADD1',2) WITH
(
Address VARCHAR(50),
State VARCHAR(50),
City VARCHAR(50),
Pincode INT
) XML;
INSERT INTO Customer_Address(Cust_Id, Address, State, City, Pincode)
SELECT #CustId AS Cust_Id, XML.Address, XML.State, XML.City, XML.Pincode
FROM OPENXML(#DOC, '/XML/Customer/Add/ADD2',2) WITH
(
Address VARCHAR(50),
State VARCHAR(50),
City VARCHAR(50),
Pincode INT
) XML;
EXEC sp_xml_removedocument #DOC;
END
Using this procedure I executed your sample xml data and it looks like below entries in both tables.
Your issue is at
(SELECT ID FROM DUMMY WHERE Name = Name)
It returns all values from DUMMY table, and causes error.
Subquery returned more than 1 value. This is not permitted when the
subquery follows =, !=, <, <= , >, >= or when the subquery is used as
an expression.
Solution:
-- After the first insert
Declare #DummyId int = scope_identity() -- get new inserted id from dummy
INSERT INTO DummyExtd
(
ID,
Address,
State,
City,
Pincode
) SELECT
#DummyId,
XML.Address,
XML.State,
XML.City,
XML.Pincode
FROM OPENXML(#DOC, '/XML/Customer/Add',2) WITH
( -- ID INT, --- Remove it, ID tag doesn't exist in your xml
Address VARCHAR(50),
State VARCHAR(50),
City VARCHAR(50),
Pincode INT
) XML;

How to throw error when no node is found using OpenXML

I would like to ask how to throw an error in SQL Server when the XML is parsed using OpenXML. Here is an example from Microsoft:
Insert Into Employee
SELECT EmployeeId, FirstName, LastName
FROM OPENXML (#hdoc, '/NewDataSet/Employee',1)
WITH (EmployeeId Integer, FirstName varchar(100), LastName varchar(100)) XMLEmployee
Where XMLEmployee.EmployeeId Not IN (Select EmployeeID from Employee)
What if the root node exists but there is no Employee in it?
Thanks
Try this one -
DECLARE #XML XML
SELECT #XML = '<NewDataSet></NewDataSet>'
IF NOT EXISTS(
SELECT 1
WHERE #XML.exist('/NewDataSet/Employee') = 1
) RAISERROR('Employee not exists', 16, 1)
Full answer (maybe wrong answer, because I need to see XML structure) -
DECLARE #XML XML
SELECT #XML = '<NewDataSet></NewDataSet>'
IF NOT EXISTS(
SELECT 1
WHERE #XML.exist('/NewDataSet/Employee') = 1
) RAISERROR('Employee not exists', 16, 1)
INSERT INTO dbo.Employee (EmployeeId, FirstName, LastName)
SELECT
t.c.value('#EmployeeId', 'INT')
, t.c.value('#FirstName', 'VARCHAR(100)')
, t.c.value('#LastName', 'VARCHAR(100)')
FROM #XML.nodes('/NewDataSet/Employee') t(c)
WHERE t.c.value('#EmployeeId', 'INT') NOT IN (
SELECT EmployeeID
FROM dbo.Employee
)

Import XML with Attribute to SQL Server Table

I can't get the value for the XML attribute 'Country' into my table.
What am I doing wrong?
Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<CustomerDetails>
<PersonalInfo Country="USA">
<CustID>1001</CustID>
<CustLastName>Smith</CustLastName>
<DOB>2011-05-05T09:25:48.253</DOB>
<Address>
<Addr1>100 Smith St.</Addr1>
<City>New York</City>
</Address>
</PersonalInfo>
</CustomerDetails>
Here is my SQL:
Drop table #Cust
CREATE TABLE #Cust
(CustID INT, CustLastName VARCHAR(10)
, DOB DATETIME, Addr1 VARCHAR(100), City VARCHAR(10), Country VARCHAR(20))
insert into #Cust
select
c3.value('CustID[1]','int'),
c3.value('CustLastName[1]','varchar(10)'),
c3.value('DOB[1]','DATETIME'),
c3.value('(Address/Addr1)[1]','VARCHAR(100)'),
c3.value('(Address/City)[1]','VARCHAR(10)'),
c3.value('Country[1]','VARCHAR(20)')
from
(
select
cast(c1 as xml)
from
OPENROWSET (BULK 'C:\Users\wattronts\Documents\XMLImportTest.xml',SINGLE_BLOB) as T1(c1)
)as T2(c2)
cross apply c2.nodes('/CustomerDetails/PersonalInfo') T3(c3)
Select * from #Cust
Thanks for your help.
Use # to specify that you want an attribute.
T3.c3.value('#Country', 'varchar(50)')

Resources