XML Cdata format and variable input TSQL - sql-server

DECLARE #TransactionId NVARCHAR(100)
DECLARE #TransactionDateTime DATETIME
--Setting Variable
SET #TransactionId= (SELECT CONVERT(VARCHAR, CURRENT_TRANSACTION_ID()))
SET #TransactionDateTime= GETDATE()
--Start the XML Selction
SELECT
1 AS Tag,
NULL AS Parent,
NULL AS 'Tag!1!',
NULL AS 'TransactionType!2!CollectSampling!cdata',
NULL AS 'TransactionID!2!TransactionId!cdata',
NULL AS 'TransactionDateTime!2!TransactionDateTime!cdata',
NULL AS 'ContainerName!2!Name!cdata',
NULL AS 'Make!2!Make!cdata',
NULL AS 'Model!2!Model!cdata',
NULL AS 'Price!2!Price!cdata',
NULL AS 'Type!2!Type!cdata'
Union ALL
SELECT
2 AS Tag,
1 AS Parent,
NULL,
'CollectSample',
#TransactionId,
#TransactionDateTime,
[Name] ,
[Make] ,
[Model] ,
[Price] ,
[Type]
from dbo.RepCar
FOR XML EXPLICIT, ROOT('Message')
The below is the output I would like to have but keep getting XML formats errors. Also just the Message is the parent
Would like output as below.I'm using variables to populate a couple of tags and CollectSample is static field.
<Message>
<TransactionType><![CDATA[CollectSamplingData]]></TransactionType>
<TransactionID><![CDATA[0CA4E46F-5143-498C-B1AC-F990FF70462E]]></TransactionID>
<TransactionDate><![CDATA[2020-01-10T14:20:30-05:00]]></TransactionDate>
<CName><![CDATA[Name]]></CName>
<MakeCar><![CDATA[Make]]></MakeCar>
<MakeModel><![CDATA[Model]]></MakeModel>
<DataValue><![CDATA[Price]]></DataValue>
<MakeType><![CDATA[Type]]></MakeType>
</Message>

declare #RepCar table
(
[Name] varchar(10),
[Make] varchar(10),
[Model] varchar(10),
[Price] money,
[Type] varchar(10)
);
insert into #RepCar
(
Name, Make, Model, Price, Type
)
values
('Car1', 'Make1', 'Model1', 100, 'Type1'),
('Car2', 'Make2', 'Model2', 200, 'Type2'),
('Car3', 'Make3', 'Model3', 300, 'Type3');
DECLARE #TransactionId NVARCHAR(100)
DECLARE #TransactionDateTime DATETIME
--Setting Variable
SET #TransactionId= (SELECT CONVERT(VARCHAR, CURRENT_TRANSACTION_ID()))
SET #TransactionDateTime= GETDATE()
--Start the XML Selction
/*
ElementName!TagNumber!AttributeName!Directive
AttributeName
Provides the name of the attribute to construct in the specified ElementName. This is the behavior if Directive is not specified.
!!!! If Directive is specified and it is xml, cdata, or element, this value is used to construct an element child of ElementName, and the column value is added to it.!!!!
*/
select 1 AS Tag,
0 AS Parent,
'CollectSamplingData' as 'Message!1!TransactionType!cdata',
#TransactionId as 'Message!1!TransactionID!cdata',
#TransactionDateTime as 'Message!1!TransactionDate!cdata',
[Name] as 'Message!1!CName!cdata',
[Make] as 'Message!1!MakeCar!cdata',
[Model] as 'Message!1!MakeModel!cdata',
[Price] as 'Message!1!DataValue!cdata',
[Type] as 'Message!1!MakeType!cdata'
from #RepCar --dbo.RepCar
FOR XML EXPLICIT, ROOT('Messages');

Related

Issue inserting into a temp table in SQL Server 2012

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;

Adventure Works 2019: Adding New Person to Person.Person Table

Right now I am using 3 stored procedures to Add a person to the person.person table. I would like to cut this down to a single stored procedure to resolve this issue.
INSERT new GUID and DateModified to table Person.BusinessEntity
SELECT the auto generate BusinessEntityID form table Person.BusinessEntity
INSERT new Person to Person.Person Table
The Stored Procedures all use parameters which I pass via a C# application and I have confirmed that the a user is in fact added to the AdventureWorks2019 Db.
Procedure: Person.CreateNewBusinessEntity
INSERT INTO [Person].[BusinessEntity]
(
[BusinessEntity].rowguid
, [BusinessEntity].ModifiedDate
)
VALUES
(
#RowGUID
, GetDate()
)
Procedure: Person.GetBusinessEntityID
SELECT
[BusinessEntityID]
FROM
[AdventureWorks2019].[Person].[BusinessEntity]
WHERE [rowguid] = #RowGuid
Procedure: Person.CreateNewPerson
INSERT INTO [Person].[Person]
(
[BusinessEntityID]
,[PersonType]
,[NameStyle]
,[Title]
,[FirstName]
,[MiddleName]
,[LastName]
,[Suffix]
,[EmailPromotion]
,[AdditionalContactInfo]
,[Demographics]
,[rowguid]
,[ModifiedDate]
)
VALUES
(
#BusinessEntityID
, #PersonType
, #NameStyle
, #Title
, #FirstName
, #MiddleName
, #LastName
, #Suffix
, #EmailPromotion
, #AdditionalContactInfo
, #Demographics
, #RowGUID
, GetDate()
)
Any help here is appreciated. Thanks!
Thanks to HABO, I am now using this solution. Now I only need two procedures.
DECLARE #Inserted table ( [BusinessEntityID] int );
INSERT INTO [Person].[BusinessEntity]
(
[BusinessEntity].rowguid
, [BusinessEntity].ModifiedDate
)
OUTPUT inserted.[BusinessEntityID] INTO #Inserted([BusinessEntityID])
VALUES
(
#RowGUID
, GetDate()
)
The below answer shows you how to get the inserted id and add it to the next insert in side the Same SP.
USE AdventureWorks2012
GO
CREATE PROC CreateNewPerson
AS
BEGIN
DECLARE #OutputTbl TABLE ([BusinessEntityID] INT, ModifiedDate DATETIME)
DECLARE #BusinessEntityID AS INT
INSERT INTO [Person].[BusinessEntity]
(
[BusinessEntity].rowguid
, [BusinessEntity].ModifiedDate
)
--Get the output value inserted to a table.
OUTPUT inserted.[BusinessEntityID], inserted.ModifiedDate INTO
#OutputTbl([BusinessEntityID],[ModifiedDate])
VALUES
(
NEWID()
, GetDate()
)
--Assigned to a variable. You can get this using subquery as well inside the insert statment.
SELECT #BusinessEntityID = [BusinessEntityID] FROM #OutputTbl
INSERT INTO [Person].[Person]
(
[BusinessEntityID]
,[PersonType]
,[NameStyle]
,[Title]
,[FirstName]
,[MiddleName]
,[LastName]
,[Suffix]
,[EmailPromotion]
,[AdditionalContactInfo]
,[Demographics]
,[rowguid]
,[ModifiedDate]
)
VALUES
(
#BusinessEntityID
, #PersonType --These columns with # sign needed to be declared or supply values
, #NameStyle
, #Title
, #FirstName
, #MiddleName
, #LastName
, #Suffix
, #EmailPromotion
, #AdditionalContactInfo
, #Demographics
, NEWID() --This will generate a new GUID for each row.
, GetDate()
)
END
GO
Second way is using Scope_identity(). Replace the
"SELECT #BusinessEntityID = [BusinessEntityID] FROM #OutputTbl'
from below lines in the Sp will do the same thing for you.
SELECT #BusinessEntityID = SCOPE_IDENTITY() --[BusinessEntityID] FROM #OutputTbl
Select #BusinessEntityID

Open XML select values with XML name space

I am trying to select some values using open xml in sql server 2012. This works when I don't have any xml name space. But whenever the below prefix get added with root element, I am not able to select values. Any suggestion how I can select values with xmlns:
xmlns="somenamspace/2006-10-31" order-no="00000001"
USE grails
GO
DECLARE #XML AS XML, #hDoc AS INT, #SQL NVARCHAR (MAX), #rootxmlns varchar(100)
SELECT #XML = N'<order xmlns="somenamspace/2006-10-31" order-no="00000001">
<order-date>2017-07-24T20:48:57.000Z</order-date>
<original-order-no>00000001</original-order-no>
<customer>
<customer-name>abcd abcd</customer-name>
<customer-email>jjj#gmail.com</customer-email>
</customer>
<current-order-no>00000001</current-order-no>
<payments>
<payment>
<credit-card>
<card-type>VISA</card-type>
<card-number>XXXX-XXXX-XXXX-1111</card-number>
<card-holder>abcd</card-holder>
<expiration-month>1</expiration-month>
<expiration-year>2021</expiration-year>
</credit-card>
<amount>325.48</amount>
</payment>
</payments>
</order>';
SET #rootxmlns = '<root xmlns:ns1="somenamspace/2006-10-31"/>'
EXEC sp_xml_preparedocument #hDoc OUTPUT, #XML, #rootxmlns
SELECT orderNo
FROM OPENXML(#hDoc, 'ns1:order',2)
WITH
(
orderNo [varchar](50) 'original-order-no'
)
SELECT *
FROM OPENXML(#hDoc, 'ns1:order/customer',2)
WITH
(
customerName [varchar](50) 'customer-name',
customerEmail [varchar](100) 'customer-email'
)
SELECT cardType, cardNumber, cardHolder
FROM OPENXML(#hDoc, '/order/payments/payment/credit-card',2)
WITH
(
cardType [varchar](50) 'card-type',
cardNumber [varchar](100) 'card-number',
cardHolder [varchar](100) 'card-holder'
)
EXEC sp_xml_removedocument #hDoc
GO
Great, that you've found an answer yourself, but this can be solved better.
FROM OPENXML with the corresponding SPs to open and to remove a document is outdated and should not be used any more. Rather use the methods, the native XML type provides:
The following will give you at least some templates how to access the values within your XML:
DECLARE #XML AS XML=
N'<order xmlns="somenamspace/2006-10-31" order-no="00000001">
<order-date>2017-07-24T20:48:57.000Z</order-date>
<original-order-no>00000001</original-order-no>
<customer>
<customer-name>abcd abcd</customer-name>
<customer-email>jjj#gmail.com</customer-email>
</customer>
<current-order-no>00000001</current-order-no>
<payments>
<payment>
<credit-card>
<card-type>VISA</card-type>
<card-number>XXXX-XXXX-XXXX-1111</card-number>
<card-holder>abcd</card-holder>
<expiration-month>1</expiration-month>
<expiration-year>2021</expiration-year>
</credit-card>
<amount>325.48</amount>
</payment>
</payments>
</order>';
--The query
WITH XMLNAMESPACES(DEFAULT N'somenamspace/2006-10-31')
SELECT #xml.value(N'(/order/#order-no)[1]',N'int') AS OrderNumber
,#xml.value(N'(/order/order-date/text())[1]',N'datetime') AS OrderDate
,#xml.value(N'(/order/customer/customer-name/text())[1]',N'nvarchar(max)') AS CustomerName
,p.value(N'local-name(.)',N'nvarchar(max)') AS PaymentType
,p.value(N'(card-type/text())[1]','nvarchar(max)') AS CardType
,p.value(N'(../amount/text())[1]','decimal(10,4)') AS Amount
FROM #xml.nodes(N'/order/payments/payment/*[local-name()!="amount"]') AS A(p)
The result
Nr OrderDate CustomerName PaymentType CardType Amount
1 2017-07-24 20:48:57.000 abcd abcd credit-card VISA 325.4800
Explanation
Some data is taken directly via XPath out of #xml. The statement FROM #xml.nodes() will create a derived table of <payments><payment> nodes (as the wording suggests a 1:n relationship. The <amount> node is handled explicitly, the other node within <payment> is taken as payment details.
Got it,need to add name space in property level as well:
SET #rootxmlns = '<root xmlns:ns1="http://www.demandware.com/xml/impex/order/2006-10-31"/>'
EXEC sp_xml_preparedocument #hDoc OUTPUT, #XML, #rootxmlns
SELECT orderNo
FROM OPENXML(#hDoc, 'ns1:order',2)
WITH
(
orderNo [varchar](50) 'ns1:original-order-no'
)
SELECT *
FROM OPENXML(#hDoc, 'ns1:order/ns1:customer',2)
WITH
(
customerName [varchar](50) 'ns1:customer-name',
customerEmail [varchar](100) 'ns1:customer-email'
)
SELECT cardType, cardNumber, cardHolder
FROM OPENXML(#hDoc, 'ns1:order/ns1:payments/ns1:payment/ns1:credit-card',2)
WITH
(
cardType [varchar](50) 'ns1:card-type',
cardNumber [varchar](100) 'ns1:card-number',
cardHolder [varchar](100) 'ns1:card-holder'
)
EXEC sp_xml_removedocument #hDoc
GO

XQuery with dynamic XPath from XML Sql Server Column

I have a log table has xml column which contains log contents
There is also table called logType which is the type of log
I need to create query descripes the xml contents as readable string
I added a column with name logXPath to logtype table
and i created the following query
SELECT contents.value(LogXPath, 'nvarchar(max)')
FROM dbo.Log
JOIN dbo.LogType ON dbo.Log.logTypeID = dbo.LogType.logTypeID
and I got the following error
The argument 1 of the XML data type method "value" must be a string literal
and I searched for a way to do this with no results!!
Is there any do dynamic xpath in Sql Server XML Column?
Edit
for example assume the following schema and data
CREATE TABLE [dbo].[logType]
(
[logTypeID] [int] NOT NULL ,
[logTypeName] [nvarchar](50) NOT NULL ,
[xPath] [nvarchar](MAX) NOT NULL ,
CONSTRAINT [PK_logType] PRIMARY KEY CLUSTERED ( [logTypeID] ASC )
)
GO
INSERT [dbo].[logType]
( [logTypeID] ,
[logTypeName] ,
[xPath]
)
VALUES ( 1 ,
N'Patient Data' ,
N'(/Patient/PatientName)[1]'
)
INSERT [dbo].[logType]
( [logTypeID] ,
[logTypeName] ,
[xPath]
)
VALUES ( 2 ,
N'Clinic Data' ,
N'(/Clinic/ClinicName)[1]'
)
/****** Object: Table [dbo].[log] Script Date: 02/04/2015 13:58:47 ******/
GO
CREATE TABLE [dbo].[log]
(
[logID] [int] NOT NULL ,
[logTypeID] [int] NOT NULL ,
[Contents] [xml] NULL ,
CONSTRAINT [PK_log] PRIMARY KEY CLUSTERED ( [logID] ASC )
)
GO
INSERT [dbo].[log]
( [logID] ,
[logTypeID] ,
[Contents]
)
VALUES ( 1 ,
1 ,
N'<Patient><PatientID>1</PatientID><PatientName>john</PatientName></Patient>'
)
INSERT [dbo].[log]
( [logID] ,
[logTypeID] ,
[Contents]
)
VALUES ( 2 ,
2 ,
N'<Clinic><ClinicID>1</ClinicID><ClinicName>Clinic 1</ClinicName></Clinic>'
)
When I make query like the following ,it gives me the error
SELECT logTypeName ,
[Contents].value(dbo.logType.xPath, 'nvarchar(max)') AS data
FROM dbo.[log]
JOIN dbo.logType ON dbo.[log].logTypeID = dbo.logType.logTypeID
You can build a query dynamically using the table LogType.
declare #SQL nvarchar(max);
set #SQL = 'select case L.logTypeID'+
(
select ' when '+cast(LT.logTypeID as varchar(11))+
' then L.Contents.value('''+LT.xPath+''', ''nvarchar(max)'')'
from LogType as LT
for xml path('')
)+' end as Name from dbo.[Log] as L;';
exec (#SQL);
It will give you a query that looks like this:
select case L.logTypeID
when 1 then L.Contents.value('(/Patient/PatientName)[1]', 'nvarchar(max)')
when 2 then L.Contents.value('(/Clinic/ClinicName)[1]', 'nvarchar(max)')
end as Name
from dbo.[Log] as L;
Okay, so this has been here a while (a year), but this might be helpful...
A VERY helpful TABLE function: http://beyondrelational.com/modules/2/blogs/28/posts/10495/xquery-lab-58-select-from-xml.aspx
Using that function, you can get the values you're after something like this:
Select l.Contents, t.XPath, x.Value
From [log] l With (NoLock)
Inner Join [LogType] t With (NoLock)
on t.LogTypeID=l.LogTypeID
CROSS APPLY XMLTable(l.Contents) AS x
Where REPLACE(REPLACE(REPLACE(t.XPath,'[1]',''),'(',''),')','')=REPLACE('/'+x.XPath,'[1]','')
SQL Server does not allow replacing entire XPath expression with a variable, but you can use sql:variable and sql:column extensions inside the expression (I can't say how exactly without seeing your xml structure and what information you want to query from XML column).
Or, as mentioned above, you can use dynamic SQL:
DECLARE #xpath NVARCHAR(MAX);
SET #xpath = ... //Calculate xpath expression here
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'SELECT contents.value(''' + #xpath + ''', ''NVARCHAR(MAX)''
FROM dbo.Log
JOIN dbo.LogType ON dbo.Log.logTypeID = dbo.LogType.logTypeID';
EXEC sp_executesql #sql;

Update columns whose vales return from a function

I have a trouble with updating the table with values which are return back from a user function, I couldn't know how to do it.
Enviroment:MsSql
DECLARE #files TABLE
(
Id uniqueidentifier,
Name nvarchar(255),
FolderId uniqueidentifier,
IsCheckedOut bit,
CheckedOutBy nvarchar(50),
IsDeleted bit,
IsVirtual bit,
Content varbinary(MAX),
FolderPath nvarchar(MAX),
CultureCode varchar(16)
)
UPDATE #files
SET Content= (SELECT TOP 1 Content FROM fnGetFileContentById (#changeListId, Id, #autoRevert,#cultureCode,#defaultCultureCode)),
CultureCode = (SELECT TOP 1 CultureCode FROM fnGetFileContentById (#changeListId, Id, #autoRevert,#cultureCode,#defaultCultureCode)),
FolderPath=(SELECT TOP 1 FullPath FROM Folder WHERE Id= FolderId)
function script
FUNCTION [dbo].[fnGetFileContentById]
(
#changeListId UNIQUEIDENTIFIER,
#fileId UNIQUEIDENTIFIER,
#autoRevert BIT,
#cultureCode VARCHAR(16),
#defaultCultureCode VARCHAR(16)
)
RETURNS #fileContent TABLE
(
Id UNIQUEIDENTIFIER PRIMARY KEY NOT NULL,
FileId UNIQUEIDENTIFIER NOT NULL,
Content VARBINARY(MAX) NOT NULL,
[Version] INT NOT NULL,
ChangeListId UNIQUEIDENTIFIER,
FileTypeId INT NOT NULL ,
CultureCode VARCHAR(16)
)
I don't want to rerun fnGetFileContentById function for updating CultureCode, How do I write this statement with one execution of fnGetGileContentById
Maybe something like this:
UPDATE #files
SET Content=FileContent.Content,
CultureCode =FileContent.CultureCode,
FolderPath= folder.FullPath
FROM #files
CROSS APPLY
(
SELECT TOP 1
Content,
CultureCode
FROM
fnGetFileContentById(#changeListId, Id, #autoRevert,#cultureCode,#defaultCultureCode)
) FileContent
CROSS APPLY
(
SELECT TOP 1
FullPath
FROM
Folder
WHERE
f.Id = FolderId
) AS folder

Resources