Showing posts with label insert. Show all posts
Showing posts with label insert. Show all posts

Monday, March 26, 2012

ForEach file enumeration with bulk insert problem

OK, a new package, with a Foreach container enumerating CSV files in a directory.

I create the container pointing it at the directory and retrieving the fully qualified name, and create a variable (called 'CSVFiles') with a package scope, but no value.

Inside the container is a bulk insert task. The destination db/table is set, and the input flat file connection manager for the CSV files is defined with the connection string set to the variable created above.

As it iterates through the files, the variable is correctly set to the next file in the directory (I put a message box in the stream to display the file name/variable). It resembles 'C:\temp\Location1.csv'.

But when it gets to the bulk insert, I get this error message:

[Bulk Insert Task] Error: The specified connection "CSVFiles" is either not valid, or points to an invalid object. To continue, specify a valid connection.

What's going on here? Can I not use a bulk insert task in the container? Or some other parameter needs to be set?

SQL Server 9.00.3159

You have to use a file connection instead of the variable.

HTH.

|||

thanks...I was typing a bit too fast on my first post.

The variable for the ForEach container is called 'CSVFN' and the connection manager name is 'CSVFiles'. In the properties for the connection manager, I changed the 'connectionstring' to equal the variable (@.[User::CSVFN]).

And on a related note, how do I use that variable in a T-SQL script in an Execute SQL task in the container (I get a syntax error about the variable not being defined)? I would like to insert the name of the file (from the variable) into a table for auditing purposes.

thx

|||

Kevin6 wrote:

thanks...I was typing a bit too fast on my first post.

The variable for the ForEach container is called 'CSVFN' and the connection manager name is 'CSVFiles'. In the properties for the connection manager, I changed the 'connectionstring' to equal the variable (@.[User::CSVFN]).

And on a related note, how do I use that variable in a T-SQL script in an Execute SQL task in the container (I get a syntax error about the variable not being defined)? I would like to insert the name of the file (from the variable) into a table for auditing purposes.

thx

You'd have to put the variable in the expression editor for the property "ConnectionString." Right click on the connection manager object and select properties. Scroll down to find "Expressions." Click the ellipsis and select ConnectionString. There is where you put the variable name.

Re: Execute SQL Task
Make sure that the variable is of package-level scope and that the Execute SQL Task can see it.
Then build a SQL statement like this:
insert into auditTable values (1,"Testing", ?)

Then click on the parameter mapping tab, click Add, and select the variable in the variable name column. Then use zero (0) for the parameter name. Change the data type to "VARCHAR". If you have another parameter, do the same, but use a one (1) in the parameter name box.

Monday, March 12, 2012

Force a commit

Hi,

My data flow has several transformations:

1. Search an employee, if the employee already exists, update it, otherwise insert it.

2. Once the new employee is created, i have to get its id (with another search transformation )to update another table with it. This id is an autonumeric , thats the reason i have to get it once the record is inserted.

At this momment this second search transformation to get the assigned id for the new reacord doesnt find any employee... i suppose its because these new data is not commited in the database....

the question is, Its possible to force a commit?

Thanks!

try to use T-SQL function IDENT_CURRENT

"IDENT_CURRENT returns the value generated for a specific table in any session and any scope."(from Books Online)

|||

thanks for your answer ggciubuc,

I have seen the IDENT_CURRENT documentation, and i think it could work if the flow process rows isolated ( ie. using a for each bucle), but in my case, the output of the oledb command transformation is a bunch of rows, so , i think that using this function i get only the last id generated... am i wrong?

Any other suggestion?

Thanks

|||

After your last post i suppose there are many clients that run your package, so there are many ID's.

But let's think at these ID's; you are got in a variable IDENT_CURRENT of time t0 an unique value of ID

if someone run the some package, the variable get another value of IDENT_CURRENT of time t1, and t0<t1

this because I thing this running of package is a consecutive running.

Try this ideea.

|||

Another ideea is to use 2 Data Flow tasks

In first you update/insert employee then you have source-transform-destination, so is made a commit and in second

you update another tables. Link with a "Constraint precedence" arrow with value "succes"

|||

thanks ggciubuc,

Thats a good solution , the problem is that the time to reatrive data source is to large. If i split in two data flows, i have to get these data two times...

For/Next loop to process INSERT INTO statement

I reposted this because I was unable to achieve desired results from
previous recommendations.
Previous Post:
=================== I have the following code which does the following:
1. Deletes all rows having a value of "0" in column C
2. Uploads the data in Row 2 to my SQL Server
What I need for the code to do is to upload all rows on the worksheet. My
thought is that I might need a For/Next Loop, but I'm not sure where in the
code to place it. Any ideas on how/where would I modify the code to enable
it to (loop through) upload all rows, or iterate on each row having
data (those not deleted by the DeleteBlankRows procedure)?
Here's my code:
======================== Private Sub DeleteBlankRows()
Dim lastrow As Long
Dim r As Long
lastrow = Range("C" & Rows.Count).End(xlUp).Row
For r = lastrow To 2 Step -1
If Application.CountIf(Cells(r, "C").Resize(1, 1), 0) = 1 Then
ActiveSheet.Rows(r).Delete
End If
Next
End Sub
Sub InsertData()
Dim oConn As Object
Dim sSQL As String
Application.ScreenUpdating = False
Set wsSheet = ActiveWorkbook.Sheets("Product Tracking")
Set oConn = CreateObject("ADODB.Connection")
oConn.Open = "Provider=sqloledb;" & _
"Data Source=xx.x.xx.xx;" & _
"Initial Catalog=xxx_xxx;" & _
"User Id=xxxx;" & _
"Password=xxxx"
sSQL = "INSERT INTO Upload_Specific " & _
"([Location], [Product Type], [Quantity], [Product Name], [Style],
[Features]) " & _
" VALUES ('" & Range("A2").Value & "', '" & Range("B2").Value & "', '" &
Range("C2").Value & "', '" & Range("D2").Value & "', '" & Range("E2").Value
& "', '" & _
Range("F2").Value & "')"
oConn.Execute sSQL
oConn.Close
Set oConn = Nothing
End Sub
Thanks in advance.Try changing
sSQL = "INSERT INTO Upload_Specific " & _
"([Location], [Product Type], [Quantity], [Product Name], [Style],
[Features]) " & _
" VALUES ('" & Range("A2").Value & "', '" & Range("B2").Value & "', '" &
Range("C2").Value & "', '" & Range("D2").Value & "', '" & Range("E2").Value
& "', '" & _
Range("F2").Value & "')"
oConn.Execute sSQL
to
For i = 2 To Range("A65536").End(xlUp).Row
sSQL = "INSERT INTO Upload_Specific " & _
"([Location], [Product Type], [Quantity], [Product Name], [Style],
[Features]) " & _
" VALUES ('" & Range("A"&i).Value & "', '" & Range("B"&i).Value & "', '" & _
Range("C"&i).Value & "', '" & Range("D"&i).Value & "', '" & _
Range("E"&i).Value & "', '" & _
Range("F"&i).Value & "')"
oConn.Execute sSQL
Next i
HTH,
Bernie
MS Excel MVP
"Doctorjones_md" <xxxDoctorjones_mdxxx@.xxxyahoo.com> wrote in message
news:uQqUzX5IHHA.1816@.TK2MSFTNGP06.phx.gbl...
>I reposted this because I was unable to achieve desired results from previous recommendations.
> Previous Post:
> ===================> I have the following code which does the following:
> 1. Deletes all rows having a value of "0" in column C
> 2. Uploads the data in Row 2 to my SQL Server
> What I need for the code to do is to upload all rows on the worksheet. My thought is that I might
> need a For/Next Loop, but I'm not sure where in the code to place it. Any ideas on how/where
> would I modify the code to enable it to (loop through) upload all rows, or iterate on each row
> having
> data (those not deleted by the DeleteBlankRows procedure)?
>
> Here's my code:
> ========================> Private Sub DeleteBlankRows()
> Dim lastrow As Long
> Dim r As Long
> lastrow = Range("C" & Rows.Count).End(xlUp).Row
> For r = lastrow To 2 Step -1
> If Application.CountIf(Cells(r, "C").Resize(1, 1), 0) = 1 Then
> ActiveSheet.Rows(r).Delete
> End If
> Next
> End Sub
> Sub InsertData()
> Dim oConn As Object
> Dim sSQL As String
> Application.ScreenUpdating = False
> Set wsSheet = ActiveWorkbook.Sheets("Product Tracking")
> Set oConn = CreateObject("ADODB.Connection")
> oConn.Open = "Provider=sqloledb;" & _
> "Data Source=xx.x.xx.xx;" & _
> "Initial Catalog=xxx_xxx;" & _
> "User Id=xxxx;" & _
> "Password=xxxx"
> sSQL = "INSERT INTO Upload_Specific " & _
> "([Location], [Product Type], [Quantity], [Product Name], [Style],
> [Features]) " & _
> " VALUES ('" & Range("A2").Value & "', '" & Range("B2").Value & "', '" &
> Range("C2").Value & "', '" & Range("D2").Value & "', '" & Range("E2").Value
> & "', '" & _
> Range("F2").Value & "')"
> oConn.Execute sSQL
> oConn.Close
> Set oConn = Nothing
> End Sub
> Thanks in advance.
>|||Bernie -- Thanks a Bunch -- that did the trick Brillantly!!
I was getting "Wrapped Around the Axle" trying to deal with Stored
Procedures and Bulk Inserts (and whatnot) -- what I originally had worked
(somewhat), but just needed some tweaking -- thanks again for you help and
quick response. :)
"Bernie Deitrick" <deitbe @. consumer dot org> wrote in message
news:OJ9VN15IHHA.4848@.TK2MSFTNGP04.phx.gbl...
> Try changing
> sSQL = "INSERT INTO Upload_Specific " & _
> "([Location], [Product Type], [Quantity], [Product Name], [Style],
> [Features]) " & _
> " VALUES ('" & Range("A2").Value & "', '" & Range("B2").Value & "', '"
> &
> Range("C2").Value & "', '" & Range("D2").Value & "', '" &
> Range("E2").Value
> & "', '" & _
> Range("F2").Value & "')"
> oConn.Execute sSQL
> to
> For i = 2 To Range("A65536").End(xlUp).Row
> sSQL = "INSERT INTO Upload_Specific " & _
> "([Location], [Product Type], [Quantity], [Product Name], [Style],
> [Features]) " & _
> " VALUES ('" & Range("A"&i).Value & "', '" & Range("B"&i).Value & "',
> '" & _
> Range("C"&i).Value & "', '" & Range("D"&i).Value & "', '" & _
> Range("E"&i).Value & "', '" & _
> Range("F"&i).Value & "')"
> oConn.Execute sSQL
> Next i
> HTH,
> Bernie
> MS Excel MVP
>
> "Doctorjones_md" <xxxDoctorjones_mdxxx@.xxxyahoo.com> wrote in message
> news:uQqUzX5IHHA.1816@.TK2MSFTNGP06.phx.gbl...
>>I reposted this because I was unable to achieve desired results from
>>previous recommendations.
>> Previous Post:
>> ===================>> I have the following code which does the following:
>> 1. Deletes all rows having a value of "0" in column C
>> 2. Uploads the data in Row 2 to my SQL Server
>> What I need for the code to do is to upload all rows on the worksheet.
>> My thought is that I might need a For/Next Loop, but I'm not sure where
>> in the code to place it. Any ideas on how/where would I modify the code
>> to enable it to (loop through) upload all rows, or iterate on each row
>> having
>> data (those not deleted by the DeleteBlankRows procedure)?
>>
>> Here's my code:
>> ========================>> Private Sub DeleteBlankRows()
>> Dim lastrow As Long
>> Dim r As Long
>> lastrow = Range("C" & Rows.Count).End(xlUp).Row
>> For r = lastrow To 2 Step -1
>> If Application.CountIf(Cells(r, "C").Resize(1, 1), 0) = 1 Then
>> ActiveSheet.Rows(r).Delete
>> End If
>> Next
>> End Sub
>> Sub InsertData()
>> Dim oConn As Object
>> Dim sSQL As String
>> Application.ScreenUpdating = False
>> Set wsSheet = ActiveWorkbook.Sheets("Product Tracking")
>> Set oConn = CreateObject("ADODB.Connection")
>> oConn.Open = "Provider=sqloledb;" & _
>> "Data Source=xx.x.xx.xx;" & _
>> "Initial Catalog=xxx_xxx;" & _
>> "User Id=xxxx;" & _
>> "Password=xxxx"
>> sSQL = "INSERT INTO Upload_Specific " & _
>> "([Location], [Product Type], [Quantity], [Product Name], [Style],
>> [Features]) " & _
>> " VALUES ('" & Range("A2").Value & "', '" & Range("B2").Value & "', '"
>> &
>> Range("C2").Value & "', '" & Range("D2").Value & "', '" &
>> Range("E2").Value
>> & "', '" & _
>> Range("F2").Value & "')"
>> oConn.Execute sSQL
>> oConn.Close
>> Set oConn = Nothing
>> End Sub
>> Thanks in advance.
>>
>|||Doctor Jones,
I have to believe that there is a way to move an entire table into a database without looping. But
I have no experience with SQL, and have never used code like yours - still, I'm glad to hear that my
(probably sub-optimal) code worked out for you.
Bernie
MS Excel MVP
"Doctorjones_md" <xxxDoctorjones_mdxxx@.xxxyahoo.com> wrote in message
news:uhXwiI6IHHA.816@.TK2MSFTNGP06.phx.gbl...
> Bernie -- Thanks a Bunch -- that did the trick Brillantly!!
> I was getting "Wrapped Around the Axle" trying to deal with Stored Procedures and Bulk Inserts
> (and whatnot) -- what I originally had worked (somewhat), but just needed some tweaking -- thanks
> again for you help and quick response. :)
>
> "Bernie Deitrick" <deitbe @. consumer dot org> wrote in message
> news:OJ9VN15IHHA.4848@.TK2MSFTNGP04.phx.gbl...
>> Try changing
>> sSQL = "INSERT INTO Upload_Specific " & _
>> "([Location], [Product Type], [Quantity], [Product Name], [Style],
>> [Features]) " & _
>> " VALUES ('" & Range("A2").Value & "', '" & Range("B2").Value & "', '" &
>> Range("C2").Value & "', '" & Range("D2").Value & "', '" & Range("E2").Value
>> & "', '" & _
>> Range("F2").Value & "')"
>> oConn.Execute sSQL
>> to
>> For i = 2 To Range("A65536").End(xlUp).Row
>> sSQL = "INSERT INTO Upload_Specific " & _
>> "([Location], [Product Type], [Quantity], [Product Name], [Style],
>> [Features]) " & _
>> " VALUES ('" & Range("A"&i).Value & "', '" & Range("B"&i).Value & "', '" & _
>> Range("C"&i).Value & "', '" & Range("D"&i).Value & "', '" & _
>> Range("E"&i).Value & "', '" & _
>> Range("F"&i).Value & "')"
>> oConn.Execute sSQL
>> Next i
>> HTH,
>> Bernie
>> MS Excel MVP
>>
>> "Doctorjones_md" <xxxDoctorjones_mdxxx@.xxxyahoo.com> wrote in message
>> news:uQqUzX5IHHA.1816@.TK2MSFTNGP06.phx.gbl...
>>I reposted this because I was unable to achieve desired results from previous recommendations.
>> Previous Post:
>> ===================>> I have the following code which does the following:
>> 1. Deletes all rows having a value of "0" in column C
>> 2. Uploads the data in Row 2 to my SQL Server
>> What I need for the code to do is to upload all rows on the worksheet. My thought is that I
>> might need a For/Next Loop, but I'm not sure where in the code to place it. Any ideas on
>> how/where would I modify the code to enable it to (loop through) upload all rows, or iterate on
>> each row having
>> data (those not deleted by the DeleteBlankRows procedure)?
>>
>> Here's my code:
>> ========================>> Private Sub DeleteBlankRows()
>> Dim lastrow As Long
>> Dim r As Long
>> lastrow = Range("C" & Rows.Count).End(xlUp).Row
>> For r = lastrow To 2 Step -1
>> If Application.CountIf(Cells(r, "C").Resize(1, 1), 0) = 1 Then
>> ActiveSheet.Rows(r).Delete
>> End If
>> Next
>> End Sub
>> Sub InsertData()
>> Dim oConn As Object
>> Dim sSQL As String
>> Application.ScreenUpdating = False
>> Set wsSheet = ActiveWorkbook.Sheets("Product Tracking")
>> Set oConn = CreateObject("ADODB.Connection")
>> oConn.Open = "Provider=sqloledb;" & _
>> "Data Source=xx.x.xx.xx;" & _
>> "Initial Catalog=xxx_xxx;" & _
>> "User Id=xxxx;" & _
>> "Password=xxxx"
>> sSQL = "INSERT INTO Upload_Specific " & _
>> "([Location], [Product Type], [Quantity], [Product Name], [Style],
>> [Features]) " & _
>> " VALUES ('" & Range("A2").Value & "', '" & Range("B2").Value & "', '" &
>> Range("C2").Value & "', '" & Range("D2").Value & "', '" & Range("E2").Value
>> & "', '" & _
>> Range("F2").Value & "')"
>> oConn.Execute sSQL
>> oConn.Close
>> Set oConn = Nothing
>> End Sub
>> Thanks in advance.
>>
>>
>|||Bernie,
There are a plethora of methods to Insert an entire Table, but your For/Next
code does exactly what I needed it to do.
Several other methods (OPENROWSET -- BULK INSERT) weren't working for me --
based on SQL Server Security Settings and/or other issues.
Thanks again for your help! :)
"Bernie Deitrick" <deitbe @. consumer dot org> wrote in message
news:eHaaO0DJHHA.4848@.TK2MSFTNGP04.phx.gbl...
> Doctor Jones,
> I have to believe that there is a way to move an entire table into a
> database without looping. But I have no experience with SQL, and have
> never used code like yours - still, I'm glad to hear that my (probably
> sub-optimal) code worked out for you.
> Bernie
> MS Excel MVP
>
> "Doctorjones_md" <xxxDoctorjones_mdxxx@.xxxyahoo.com> wrote in message
> news:uhXwiI6IHHA.816@.TK2MSFTNGP06.phx.gbl...
>> Bernie -- Thanks a Bunch -- that did the trick Brillantly!!
>> I was getting "Wrapped Around the Axle" trying to deal with Stored
>> Procedures and Bulk Inserts (and whatnot) -- what I originally had worked
>> (somewhat), but just needed some tweaking -- thanks again for you help
>> and quick response. :)
>>
>> "Bernie Deitrick" <deitbe @. consumer dot org> wrote in message
>> news:OJ9VN15IHHA.4848@.TK2MSFTNGP04.phx.gbl...
>> Try changing
>> sSQL = "INSERT INTO Upload_Specific " & _
>> "([Location], [Product Type], [Quantity], [Product Name], [Style],
>> [Features]) " & _
>> " VALUES ('" & Range("A2").Value & "', '" & Range("B2").Value & "',
>> '" &
>> Range("C2").Value & "', '" & Range("D2").Value & "', '" &
>> Range("E2").Value
>> & "', '" & _
>> Range("F2").Value & "')"
>> oConn.Execute sSQL
>> to
>> For i = 2 To Range("A65536").End(xlUp).Row
>> sSQL = "INSERT INTO Upload_Specific " & _
>> "([Location], [Product Type], [Quantity], [Product Name], [Style],
>> [Features]) " & _
>> " VALUES ('" & Range("A"&i).Value & "', '" & Range("B"&i).Value & "',
>> '" & _
>> Range("C"&i).Value & "', '" & Range("D"&i).Value & "', '" & _
>> Range("E"&i).Value & "', '" & _
>> Range("F"&i).Value & "')"
>> oConn.Execute sSQL
>> Next i
>> HTH,
>> Bernie
>> MS Excel MVP
>>
>> "Doctorjones_md" <xxxDoctorjones_mdxxx@.xxxyahoo.com> wrote in message
>> news:uQqUzX5IHHA.1816@.TK2MSFTNGP06.phx.gbl...
>>I reposted this because I was unable to achieve desired results from
>>previous recommendations.
>> Previous Post:
>> ===================>> I have the following code which does the following:
>> 1. Deletes all rows having a value of "0" in column C
>> 2. Uploads the data in Row 2 to my SQL Server
>> What I need for the code to do is to upload all rows on the worksheet.
>> My thought is that I might need a For/Next Loop, but I'm not sure where
>> in the code to place it. Any ideas on how/where would I modify the
>> code to enable it to (loop through) upload all rows, or iterate on each
>> row having
>> data (those not deleted by the DeleteBlankRows procedure)?
>>
>> Here's my code:
>> ========================>> Private Sub DeleteBlankRows()
>> Dim lastrow As Long
>> Dim r As Long
>> lastrow = Range("C" & Rows.Count).End(xlUp).Row
>> For r = lastrow To 2 Step -1
>> If Application.CountIf(Cells(r, "C").Resize(1, 1), 0) = 1 Then
>> ActiveSheet.Rows(r).Delete
>> End If
>> Next
>> End Sub
>> Sub InsertData()
>> Dim oConn As Object
>> Dim sSQL As String
>> Application.ScreenUpdating = False
>> Set wsSheet = ActiveWorkbook.Sheets("Product Tracking")
>> Set oConn = CreateObject("ADODB.Connection")
>> oConn.Open = "Provider=sqloledb;" & _
>> "Data Source=xx.x.xx.xx;" & _
>> "Initial Catalog=xxx_xxx;" & _
>> "User Id=xxxx;" & _
>> "Password=xxxx"
>> sSQL = "INSERT INTO Upload_Specific " & _
>> "([Location], [Product Type], [Quantity], [Product Name], [Style],
>> [Features]) " & _
>> " VALUES ('" & Range("A2").Value & "', '" & Range("B2").Value & "',
>> '" &
>> Range("C2").Value & "', '" & Range("D2").Value & "', '" &
>> Range("E2").Value
>> & "', '" & _
>> Range("F2").Value & "')"
>> oConn.Execute sSQL
>> oConn.Close
>> Set oConn = Nothing
>> End Sub
>> Thanks in advance.
>>
>>
>>
>

Friday, March 9, 2012

FOR XML Output

How do I get an output from the query below (1) one
record at a time, (2) insert the output one row at a time
into a XMLType column of a table? In addition, how do I
assign the output to a variable before step (2) so that I
can manipulate the output?
select CustomerID as "@.ID",
(select OrderID as "data()"
from Orders
where Customers.CustomerID=Orders.CustomerID
FOR XML PATH('')
) as "@.OrderIDs",
CompanyName,
ContactTitle as "ContactName/@.ContactTitle",
ContactName as "ContactName/text()",
PostalCode as "Address/@.ZIP",
Address as "Address/Street",
City as "Address/City"
FROM Customers
FOR XML PATH('Customer')
***Please disregard the new Path feature in Yukon
Thanks,
C TO
I presume you use SQL Server 2005 Express or Beta 2.
If you need to insert each customer info in XML format into a separate row
of another table you can do (I use FOR XML ..., TYPE for FOR XML to generate
XML type directly):
insert into your_table_with_xml_col
select
(select CustomerID as "@.ID",
(select OrderID as "data()"
from Orders
where Customers.CustomerID=Orders.CustomerID
FOR XML PATH('')
) as "@.OrderIDs",
CompanyName,
ContactTitle as "ContactName/@.ContactTitle",
ContactName as "ContactName/text()",
PostalCode as "Address/@.ZIP",
Address as "Address/Street",
City as "Address/City"
for xml path('Customer'), TYPE
)
FROM Customers
If you want all customers into an XML variable you can write:
declare @.x xml
set @.x=
(select CustomerID as "@.ID",
(select OrderID as "data()"
from Orders
where Customers.CustomerID=Orders.CustomerID
FOR XML PATH('')
) as "@.OrderIDs",
CompanyName,
ContactTitle as "ContactName/@.ContactTitle",
ContactName as "ContactName/text()",
PostalCode as "Address/@.ZIP",
Address as "Address/Street",
City as "Address/City"
FROM Customers
FOR XML PATH('Customer'), TYPE
)
Does it answer your question?
Regards,
Eugene
This posting is provided "AS IS" with no warranties, and
confers no rights.
"C TO" <anonymous@.discussions.microsoft.com> wrote in message
news:867101c47843$77008040$a601280a@.phx.gbl...
> How do I get an output from the query below (1) one
> record at a time, (2) insert the output one row at a time
> into a XMLType column of a table? In addition, how do I
> assign the output to a variable before step (2) so that I
> can manipulate the output?
>
<skip/>
> Thanks,
> C TO
|||Dear Eugene,
Beautiful!!!!!
Thanks, thank, thanks!!!
TO

>--Original Message--
>I presume you use SQL Server 2005 Express or Beta 2.
>If you need to insert each customer info in XML format
into a separate row
>of another table you can do (I use FOR XML ..., TYPE for
FOR XML to generate
>XML type directly):
>insert into your_table_with_xml_col
>select
> (select CustomerID as "@.ID",
> (select OrderID as "data()"
> from Orders
> where Customers.CustomerID=Orders.CustomerID
> FOR XML PATH('')
> ) as "@.OrderIDs",
> CompanyName,
> ContactTitle as "ContactName/@.ContactTitle",
> ContactName as "ContactName/text()",
> PostalCode as "Address/@.ZIP",
> Address as "Address/Street",
> City as "Address/City"
> for xml path('Customer'), TYPE
> )
>FROM Customers
>If you want all customers into an XML variable you can
write:
>declare @.x xml
>set @.x=
>(select CustomerID as "@.ID",
> (select OrderID as "data()"
> from Orders
> where Customers.CustomerID=Orders.CustomerID
> FOR XML PATH('')
> ) as "@.OrderIDs",
> CompanyName,
> ContactTitle as "ContactName/@.ContactTitle",
> ContactName as "ContactName/text()",
> PostalCode as "Address/@.ZIP",
> Address as "Address/Street",
> City as "Address/City"
> FROM Customers
> FOR XML PATH('Customer'), TYPE
>)
>Does it answer your question?
>Regards,
>Eugene
>--
>This posting is provided "AS IS" with no warranties, and
>confers no rights.
>"C TO" <anonymous@.discussions.microsoft.com> wrote in
message[vbcol=seagreen]
>news:867101c47843$77008040$a601280a@.phx.gbl...
time[vbcol=seagreen]
I
><skip/>
>
>.
>

For xml into insert

Hi,
For reasons beyond the scope of this question, i need to insert into a
varchar field of a table, the output of a select * from table2 for xml auto,
elements .
I haven't figured out a way to do this. any ideas?
thanksHello Ishmael,

> For reasons beyond the scope of this question, i need to insert into a
> varchar field of a table, the output of a select * from table2 for xml
> auto, elements . I haven't figured out a way to do this. any ideas?
If you are using SQL Server 2000, you'll need to do this via a round trip
due to the way that the XML Aggregator works -- have some client fetch the
XML and then insert it into the target table column. If you are using SQL
Server 2005, it's pretty easy:
insert into schema.tabke values (xmlCol)
select ... for xml auto,elements
Thank you,
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/

For xml into insert

Hi,
For reasons beyond the scope of this question, i need to insert into a
varchar field of a table, the output of a select * from table2 for xml auto,
elements .
I haven't figured out a way to do this. any ideas?
thanks
Hello Ishmael,

> For reasons beyond the scope of this question, i need to insert into a
> varchar field of a table, the output of a select * from table2 for xml
> auto, elements . I haven't figured out a way to do this. any ideas?
If you are using SQL Server 2000, you'll need to do this via a round trip
due to the way that the XML Aggregator works -- have some client fetch the
XML and then insert it into the target table column. If you are using SQL
Server 2005, it's pretty easy:
insert into schema.tabke values (xmlCol)
select ... for xml auto,elements
Thank you,
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/

for xml hierarchy

Hi

I have a table that looks like this

declare @.VC table ( V varchar(100), VC int, depth tinyint)
insert into @.VC values ( 'TN', 1, 1)
insert into @.VC values ( 'TN', 2, 2);

and I have for xml query

select
V as @.value,
(
select VC as '@.value' from @.VC pe where pe.V = n.V
for xml path ('Value'), root('Values'), type
) as ME
from ( select distinct VC from @.VC ) n
for xml path ('Value'), root('Values')

that gives me something like this

<Values>
<Value value="TN">
<ME>
<Values>
<Value value="1" />
<Value value="2" />
</Values>
</ME>
</Value>
</Values>

However I need to reorder the xml to look like this according to depth

<Values>
<Value value="TN">
<ME>
<Values depth = 1>
<Value value="1" />
</Values>
</ME>
<ME>
<Values depth =2>
<Value value="2" />
</Values>
</ME>
</Value>
</Values>

the problem I am having is that depth 2 is not below depth 1 node, is on the same depth with the depth attribute diff.

Is there some way to write the for xml to do this

thanks

P


select
V as "@.value",
(
select pe.depth as "Values/@.depth",
pe.VC as "Values/Value/@.value"
from @.VC pe where pe.V = n.V
for xml path('ME'),type
)
from ( select distinct V from @.VC ) n
for xml path ('Value'), root('Values')

Wednesday, March 7, 2012

FOR XML EXPLICIT - Insert XML Data into a different Table

Greetings,
How do I insert the XML document returned from the usage of FOR XML Explicit
into a different table within a Stored Procedure.
I have been able to use the FOR XML Explicit to generate the XML document
but I need to insert it into a different table as a Text value.
TIA,
KOYIf you are using SQL Server 2005, you can just insert it. In SQL Server
2000, FOR XML results have to be returned to the client-side. So you would
have to write an OLEDB/ADO program that returns the data and then reinserts
it. If you need to drive it from the server, you can use the sp_OA stored
procs.
But the best thing would be to get the April CTP of SQL Server 2005 if
running Beta software is an option...
Best regards
Michael
"Kayode Yusuf" <KayodeYusuf@.discussions.microsoft.com> wrote in message
news:8693AAA4-B0BE-4926-A179-2039BC811F1C@.microsoft.com...
> Greetings,
> How do I insert the XML document returned from the usage of FOR XML
> Explicit
> into a different table within a Stored Procedure.
> I have been able to use the FOR XML Explicit to generate the XML document
> but I need to insert it into a different table as a Text value.
> TIA,
> KOY

FOR XML EXPLICIT - Insert XML Data into a different Table

Greetings,
How do I insert the XML document returned from the usage of FOR XML Explicit
into a different table within a Stored Procedure.
I have been able to use the FOR XML Explicit to generate the XML document
but I need to insert it into a different table as a Text value.
TIA,
KOY
If you are using SQL Server 2005, you can just insert it. In SQL Server
2000, FOR XML results have to be returned to the client-side. So you would
have to write an OLEDB/ADO program that returns the data and then reinserts
it. If you need to drive it from the server, you can use the sp_OA stored
procs.
But the best thing would be to get the April CTP of SQL Server 2005 if
running Beta software is an option...
Best regards
Michael
"Kayode Yusuf" <KayodeYusuf@.discussions.microsoft.com> wrote in message
news:8693AAA4-B0BE-4926-A179-2039BC811F1C@.microsoft.com...
> Greetings,
> How do I insert the XML document returned from the usage of FOR XML
> Explicit
> into a different table within a Stored Procedure.
> I have been able to use the FOR XML Explicit to generate the XML document
> but I need to insert it into a different table as a Text value.
> TIA,
> KOY

FOR XML Explicit

Greetings,
How do I insert the XML document returned from the usage of FOR XML Explicit
into a different table within a Stored Procedure.
I have been able to use the FOR XML Explicit to generate the XML document
but I need to insert it into a different table as a Text value.
TIA,
KOYI don't think you can do this directly with T-SQL in SQL Server 2000. You
will probably need an application to do this.
I thought perhaps you could create a temp table with a single ntext field
and then do INSERT #temp SELECT ... FOR XML EXPLICIT, but the INSERT
statement doesn't allow you to use the FOR XML clause.
If your system can handle the transfer to the TEXT field being done in
batch-mode, rather than immediately, you could have an app that was launched
by SQL Agent that read the XML in and then inserted the text into a text
field; cheesy but do-able.
Mike|||Unfortunately, you will have to extract the data out and then import back
in. Some archive to get you started.
http://groups.google.co.uk/groups?q...ver+oj+textcopy
-oj
"Kayode Yusuf" <KayodeYusuf@.discussions.microsoft.com> wrote in message
news:14FF705A-EC18-4FC0-ABFE-18041AC132B4@.microsoft.com...
> Greetings,
> How do I insert the XML document returned from the usage of FOR XML
> Explicit
> into a different table within a Stored Procedure.
> I have been able to use the FOR XML Explicit to generate the XML document
> but I need to insert it into a different table as a Text value.
> TIA,
> KOY

Sunday, February 26, 2012

FOR UPDATE Trigger on Subscriber Table Won't Fire

Jim,
it is possible that your publisher update is being
replicated as an delete/insert pair. You can run profiler
to check if this is the case. If so, there is a trace flag
to keep singleton updates replicated as updates. See this
article: http://support.microsoft.com/default.aspx?
scid=http://support.microsoft.com:80/support/kb/articles/q3
02/3/41.ASP&NoWebContent=1
HTH,
Paul Ibison
Thank you! It is indeed being sent as a delete/insert pair.
"Paul Ibison" <Paul.Ibison@.Pygmalion.Com> wrote in message
news:1d51501c45383$f7401610$a001280a@.phx.gbl...
> Jim,
> it is possible that your publisher update is being
> replicated as an delete/insert pair. You can run profiler
> to check if this is the case. If so, there is a trace flag
> to keep singleton updates replicated as updates. See this
> article: http://support.microsoft.com/default.aspx?
> scid=http://support.microsoft.com:80/support/kb/articles/q3
> 02/3/41.ASP&NoWebContent=1
> HTH,
> Paul Ibison
>

For NULL

Hello Everybody
When I do Insert query for table targeting selected columns
it has to store NULL value for rest of the columns,
without going into design and click NULL for each column ,
is there any other way to set once for all, that is to be
applicable to all tables?On Mar 22, 10:20 pm, spaulsa...@.yahoo.co.in wrote:
> Hello Everybody
> When I do Insert query for table targeting selected columns
> it has to store NULL value for rest of the columns,
> without going into design and click NULL for each column ,
> is there any other way to set once for all, that is to be
> applicable to all tables?
Select the table and columns from information_schema.columns and write
a query to ALTER TABLE ALTER COLUMN with NULL

For NULL

Hello Everybody
When I do Insert query for table targeting selected columns
it has to store NULL value for rest of the columns,
without going into design and click NULL for each column ,
is there any other way to set once for all, that is to be
applicable to all tables?
On Mar 22, 10:20 pm, spaulsa...@.yahoo.co.in wrote:
> Hello Everybody
> When I do Insert query for table targeting selected columns
> it has to store NULL value for rest of the columns,
> without going into design and click NULL for each column ,
> is there any other way to set once for all, that is to be
> applicable to all tables?
Select the table and columns from information_schema.columns and write
a query to ALTER TABLE ALTER COLUMN with NULL

For NULL

Hello Everybody
When I do Insert query for table targeting selected columns
it has to store NULL value for rest of the columns,
without going into design and click NULL for each column ,
is there any other way to set once for all, that is to be
applicable to all tables?On Mar 22, 10:20 pm, spaulsa...@.yahoo.co.in wrote:
> Hello Everybody
> When I do Insert query for table targeting selected columns
> it has to store NULL value for rest of the columns,
> without going into design and click NULL for each column ,
> is there any other way to set once for all, that is to be
> applicable to all tables?
Select the table and columns from information_schema.columns and write
a query to ALTER TABLE ALTER COLUMN with NULL

Friday, February 24, 2012

For Insert/After Insert -- Default Trigger Question

Hello,
I am a little between For Insert and After Insert statements on
Triggers. I just need to know which is the Sql Server Default Trigger. Her
e
are 2 sample Triggers. Is For Insert or After Insert the default?
---
CREATE TRIGGER my_trig
ON my_table
FOR INSERT
AS
IF UPDATE(b)
PRINT 'Column b Modified'
GO
---
Create Trigger Update_Status
On ACRPLU AFTER INSERT
As
Update A Set A.a1updt = 'D'
From ACRPLU A
Where (A.a1updt = '' Or IsNull(A.a1updt, -1) < 0) And A.PK
In(Select Distinct PK From Inserted)
---
Thanks.
RichRich,
From BOL:
AFTER is the default, if FOR is the only keyword specified.
HTH
Jerry
"Rich" <Rich@.discussions.microsoft.com> wrote in message
news:6A02BEF5-E7A3-44DF-B6B3-6C26E336A319@.microsoft.com...
> Hello,
> I am a little between For Insert and After Insert statements on
> Triggers. I just need to know which is the Sql Server Default Trigger.
> Here
> are 2 sample Triggers. Is For Insert or After Insert the default?
> ---
> CREATE TRIGGER my_trig
> ON my_table
> FOR INSERT
> AS
> IF UPDATE(b)
> PRINT 'Column b Modified'
> GO
> ---
> Create Trigger Update_Status
> On ACRPLU AFTER INSERT
> As
> Update A Set A.a1updt = 'D'
> From ACRPLU A
> Where (A.a1updt = '' Or IsNull(A.a1updt, -1) < 0) And A.PK
> In(Select Distinct PK From Inserted)
> ---
> Thanks.
> Rich
>|||AFTER is the default. In other words "AFTER INSERT" means the same as "FOR
INSERT".
David Portas
SQL Server MVP
--
"Rich" wrote:

> Hello,
> I am a little between For Insert and After Insert statements on
> Triggers. I just need to know which is the Sql Server Default Trigger. H
ere
> are 2 sample Triggers. Is For Insert or After Insert the default?
> ---
> CREATE TRIGGER my_trig
> ON my_table
> FOR INSERT
> AS
> IF UPDATE(b)
> PRINT 'Column b Modified'
> GO
> ---
> Create Trigger Update_Status
> On ACRPLU AFTER INSERT
> As
> Update A Set A.a1updt = 'D'
> From ACRPLU A
> Where (A.a1updt = '' Or IsNull(A.a1updt, -1) < 0) And A.PK
> In(Select Distinct PK From Inserted)
> ---
> Thanks.
> Rich
>|||Thanks all for your replies. If I understand the explanations correctly,
what I am interpreting is that
CREATE TRIGGER my_trig
ON my_table
FOR INSERT
...
is the same as
CREATE TRIGGER my_trig
ON my_table
After INSERT
...
Is this correct? This is where my confusion lies.
Thanks,
Rich|||Yes.
"Rich" <Rich@.discussions.microsoft.com> wrote in message
news:E21BD983-4695-4D7C-A9EE-854749B1D70B@.microsoft.com...
> Thanks all for your replies. If I understand the explanations correctly,
> what I am interpreting is that
> CREATE TRIGGER my_trig
> ON my_table
> FOR INSERT
> ...
> is the same as
> CREATE TRIGGER my_trig
> ON my_table
> After INSERT
> ...
> Is this correct? This is where my confusion lies.
> Thanks,
> Rich|||Thanks. But to take this one step further, since For and After seem to be
the same, is it possible to do this?
CREATE TRIGGER my_trig
ON my_table INSERT
...
where I don't include a For or After? Is this what is meant by default
trigger?
"Jerry Spivey" wrote:

> Yes.
> "Rich" <Rich@.discussions.microsoft.com> wrote in message
> news:E21BD983-4695-4D7C-A9EE-854749B1D70B@.microsoft.com...
>
>|||No.
"Rich" <Rich@.discussions.microsoft.com> wrote in message
news:11EBA02F-433D-410A-ABAD-34CAB173E453@.microsoft.com...
> Thanks. But to take this one step further, since For and After seem to be
> the same, is it possible to do this?
> CREATE TRIGGER my_trig
> ON my_table INSERT
> ...
> where I don't include a For or After? Is this what is meant by default
> trigger?
>
> "Jerry Spivey" wrote:
>|||Yes; in earlier versions of SQL Server we only had one kind of trigger, so
we didn't need to say instead of or after. We had a trigger FOR an
operation, and it always fired AFTER the operation took place.
When INSTEAD OF triggers were added, we needed a way to make sure we
differentiated the two kinds of triggers, so AFTER was introduced as a
synonym for FOR.
So really, there is no default. You have to specify when the trigger fires,
either with FOR or AFTER (which are the same) or INSTEAD OF.
--
HTH
Kalen Delaney, SQL Server MVP
www.solidqualitylearning.com
"Rich" <Rich@.discussions.microsoft.com> wrote in message
news:E21BD983-4695-4D7C-A9EE-854749B1D70B@.microsoft.com...
> Thanks all for your replies. If I understand the explanations correctly,
> what I am interpreting is that
> CREATE TRIGGER my_trig
> ON my_table
> FOR INSERT
> ...
> is the same as
> CREATE TRIGGER my_trig
> ON my_table
> After INSERT
> ...
> Is this correct? This is where my confusion lies.
> Thanks,
> Rich
>|||Thanks everyone, again for all the explanations. So if I am not using an
Instead Of trigger, then I can write
Create Trigger...For Update...For Insert...For Delete
or
Create Trigger...After Update...After Insert...After Delete
And it is the same thing. I think I get it now.
Many thanks for all the help.
Rich
"Rich" wrote:

> Hello,
> I am a little between For Insert and After Insert statements on
> Triggers. I just need to know which is the Sql Server Default Trigger. H
ere
> are 2 sample Triggers. Is For Insert or After Insert the default?
> ---
> CREATE TRIGGER my_trig
> ON my_table
> FOR INSERT
> AS
> IF UPDATE(b)
> PRINT 'Column b Modified'
> GO
> ---
> Create Trigger Update_Status
> On ACRPLU AFTER INSERT
> As
> Update A Set A.a1updt = 'D'
> From ACRPLU A
> Where (A.a1updt = '' Or IsNull(A.a1updt, -1) < 0) And A.PK
> In(Select Distinct PK From Inserted)
> ---
> Thanks.
> Rich
>

FOR INSERT Trigger

I've got 2 tables to collect orders. The ORDERS table collects the name,
totals etc. The DETAILS table collects the products. One product per each
row. When a customer places an order, their CType field may get populated
with QW. If CType = 'QW', With a trigger, I need to add a product to the
DETAILS table. The following doesn't work, but should give you an idea what
I need.
IF (SELECT ORDERS.CType FROM AffOrders) = 'QW'
INSERT INTO DETAILS
(OrderID, OrderNo, Description, Qty, PriceEach)
VALUES (ORDERS.OrderID,'SF','ServiceFee',1,4)
How do I get this done? Obviously, I need to query the order that was just
placed. I also need to place the corresponding OrderID into DETAILS.
thanks!Try this:
CREATE TRIGGER Orders_TrigAddQWDetails
ON dbo.Orders
FOR INSERT
As
Insert DETAILS (OrderID, OrderNo,
Description, Qty, PriceEach)
Select OrderID,'SF','ServiceFee',1,4
From Inserted Where CType = 'QW'
"shank" wrote:

> I've got 2 tables to collect orders. The ORDERS table collects the name,
> totals etc. The DETAILS table collects the products. One product per each
> row. When a customer places an order, their CType field may get populated
> with QW. If CType = 'QW', With a trigger, I need to add a product to the
> DETAILS table. The following doesn't work, but should give you an idea wha
t
> I need.
>
> IF (SELECT ORDERS.CType FROM AffOrders) = 'QW'
> INSERT INTO DETAILS
> (OrderID, OrderNo, Description, Qty, PriceEach)
> VALUES (ORDERS.OrderID,'SF','ServiceFee',1,4)
> How do I get this done? Obviously, I need to query the order that was just
> placed. I also need to place the corresponding OrderID into DETAILS.
> thanks!
>
>