i have to write a script that converts a string from a MSSQL Server database in sql_latin1_general_cp1_ci_as into a value in an XML file, which is in UTF8 encoding.
Does anyone have an idea how to do in in VBS?
Thanks!
you might need to add a bit more context to your question, but a first answer would be to query the database using ADODB, load your XML into MSXML2, use XPath to select the node in which you want to add your result then insert the string as the node text.
''#open the data
dim ado: set ado = CreateObject("ADODB.Connection")
ado.ConnectionString = "..."
ado.open
dim rs: set rs = ado.Execute("SELECT TOP 1 your_string FROM your_data_table")
''#open the XML
dim xmldoc: set xmldoc = CreateObject("MSXML2.DomDocument")
xmldoc.async = false
xmldoc.setProperty "SelectionLanguage", "XPath"
''# you might also need setProperty "SelectionNamespaces", "xmlns=..." depending on your XML
xmldoc.load "path\to\your\XML"
''# store the string in the XML and save
xmldoc.selectSingleNode("//xpath/to/your/target/node").text = rs.fields["your_string"].value
xmldoc.save "path\to\your\output\xml"
rs.close
ado.close
If you're already at this point, let me know if you are having any specific problems
Related
I have a CSV File I am parsing (it's specific, so I can't just dump it in). In one of the fields, there can be a degrees sign. As an example:
TR,TIC593_SP_TREND,,TIC593_SP,0,200,°F,1,YES,NONE,NONE,NONE,,,,NONE,YES,NO,REJECT,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
That is what It looks like in NotePad and I need to be able to replicate that into the database. All of the fields I am inserting into are NVARCHAR(Max).
EDIT
What I need is for the Degrees sign to be stored in SQL Server as a degrees sign, so that when I pull it out, it will go into the newly generated CSV file as a degrees sign instead of funky characters (�F is what I see when I export the same field from SQL)
/EDIT
Code-Wise, I am doing the following:
Iterating through all lines in the CSV File to pull out the lines I want to go into the database
Creating a Datatable:
Dim sqlstr = "select * from Tags where id=-1"
adap = New SqlDataAdapter(sqlstr, conn)
Dim dt As New DataTable
adap.Fill(dt)
Creating a New DataRow
Dim _new As DataRow = dt.NewRow
For i As Integer = 0 To columnsNames.Length - 1
Application.DoEvents()
Dim colName As String = columnsNames(i).Replace("!", "")
Dim colVal As String = columnValues(i)
If colName <> "" Then
_new("NodeName") = nodeName
_new("FileName") = FileName
_new(colName) = colVal
End If
Adding to the Datatable:
dt.Rows.Add(_new)
And, Finally, committing the information to the table:
dim combld as new SQLCommandBuilder(adap)
adap.Update(dt)
I'm sure there has to be an easy way, just haven't come across it with all the searching I've done (which, hopefully, my search techniques are not the problem!).
Thanks in advance.
I've been struggling all afternoon with trying to save a zip file in a varbinary(MAX) column in SQL Server. I think I've got the zip file saved as a binary array, but I just can't seem to get it saved to the database.
My connection:
Dim objConnection As OleDbConnection
Dim objCommand As OleDbCommand
objConnection = New OleDbConnection(strConn)
objConnection.Open()
Saving the zip file from disk to a binary array:
Dim filePath As String = Session("ZipFileName")
Dim filename As String = Path.GetFileName(filePath)
Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader = New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
And then (trying to) save the file to my database:
strSQL = "UPDATE MyTable SET BinFile = #Data WHERE RecordID = '" & Session("RecName") & "'"
objCommand = New OleDbCommand(strSQL, objConnection)
objCommand.Parameters.AddWithValue("#Data", SqlDbType.Binary).Value = bytes
objCommand.ExecuteNonQuery()
I've been trying different variations of this idea for hours, including a handful from this site, but I keep getting the error
Must declare the scalar variable '#Data'
Can anyone help? Thanks.
As Plutonix suggests, your use of AddWithValue is incorrect. The whole point of AddWithValue is that you provide the name and value and the rest is inferred. The way you're calling it is what you would do with Add rather than AddWithValue, i.e. specify the type of the parameter yourself and then set the Value property afterwards. AddWithValue exists specifically so that you don;t have to do that.
Also, given that you are already doing the right thing and using a parameter for the BinFile column, why then break the rules and use string concatenation for the RecordID? Just do the right thing again and use parameters for both.
I am attempting to use XML that was generated from a stored procesure in our MS SQL database as a Recordset in a VS2005 Application. The issue I am having is that when reading in the xml as a string, the string result comes in as "System.Byte[]". Seeing this I changed the datatype from String to Byte() and tried to use the Byte array. The Byte array does not seem to have anything to do with the data I want to be receiving. I am wondering if there is a way to handle SQL generated XML files that I am not aware of. Here is some sample code.
This is what the result of the stored procedure looks like when in SQL SMS
With this code I get the System.byte[] as my string:
Dim ADOrs As ADODB.Recordset
Dim SQLString1 As New System.Text.StringBuilder(180)
Dim catzzz as String
SQLString1.Append("exec reports_selectReportMetaData #companyCode = '001'")
ADOrs = fnReturnRecordset(SQLString1.ToString) 'function executes the query
Do While Not ADOrs.EOF
catzzz = ADOrs("XML_F52E2B61-18A1-11d1-B105-00805F49916B").Value.ToString
Debug.WriteLine(catzzz)
Loop
This is the way I get the really odd Byte Array
Dim ADOrs As ADODB.Recordset
Dim SQLString1 As New System.Text.StringBuilder(180)
Dim catzzz As Byte()
SQLString1.Append("exec reports_selectReportMetaData #companyCode = '001'")
ADOrs = fnReturnRecordset(SQLString1.ToString)'function executes the query
Do While Not ADOrs.EOF
catzzz = ADOrs("XML_F52E2B61-18A1-11d1-B105-00805F49916B").Value
Loop
The Byte array looks like
And when converted to ASCII using
catX = System.Text.Encoding.Default.GetString(catzzz)
the first three characters (that should be <rt ) Come up as
So I think my main issue is that I am missing the proper way to bring in the XML created in SQL
Any Ideas would be appricated!
Ended up changing from a stored procedure to a function so that we would be returend a value instead of just having the command executed. This solved the System.Byte[] issue.
I am relatively new to SQL Server and am working on a legacy app in Visual Basic 6. How can I use an SQL INSERT command to insert a string of characters that can include any ASCII character between 0 and 255 into a VARCHAR field?
You could encode the string into a sequence of hexadecimal values representing the ASCII codes of the string's characters, put 0x in front of the sequence, then apply CAST(… AS varchar(n)) to the whole thing and use that expression in your DDL statement.
What I mean is, if your string was e.g. #X?!v, you would insert it like this
UPDATE table
SET column = CAST(0x23583F2176 AS varchar(n))
WHERE condition
So, if there was a NUL character somewhere, the resulting sequence would contain 00 at the corresponding position.
I don't really "speak" VB, but if I did, I would perhaps look into creating a function accepting a raw string and returning a string of hex codes, and so, when building the DDL command, my VB instruction would probably look something like this:
cmd.CommandText = "UPDATE table SET column = CAST(0x" & HexEncode(RawString) & " AS varchar(n)) WHERE condition"
Assuming your project has a reference to ADO, it's something like this:
Dim oConn As Connection
Dim oCmd As Command
Set oConn = New Connection
oConn.Open <your connection string goes here>
Set oCmd = New Command
oCmd.ActiveConnection = oConn
oCmd.CommandText = "INSERT INTO TableName (ColumnName) VALUES('string')"
oCmd.Execute
I don't have the ADO parameter syntax at hand, but you should be able to insert general strings (including NULs) into varchar columns using ADO Parameters.
Using classic asp, I am trying to query a SQL Server database like so:
strSQL = "select column_1, column_2, column_3, column_4 from someview " &_
"where RecordNo=" & i
set rs=conn.Execute(strSQL)
if not rs.eof then
A = rs("column_1")
B = rs("column_2")
C = rs("column_3")
D = rs("column_4")
end if
Column_3 is an NText type, the other columns are varchar or int (sometimes there may be more than 4 columns returned) but the query only returns 1 record because of the where clause.
On the ASP page the results vary - sometimes A,B,D are populated, sometimes not - but all columns in the view contain data (when I query the SQL Server I see the expected results - all columns do contain data). If I remove column_3 which is NText from the strSQL everything works fine.
I've seen this behaviour on a couple other pages in the past. If I modify the ASP to get column_3 separately:
strSQL = "select column_3 from someview where RecordNo=" & i
The NText data is returned correctly.
Is there a maximum record length to a SQL Server recordset returned to classic ASP? Apart from splitting out the NTEXT into a separate query, is there anything else I can do?
EDIT: It just occured to me to try changing the connection string - inspired by this comment on a similar problem - the connection is via SQL Server ODBC Driver (Driver={SQL Server};).
I have had this problem. Microsoft acknowledge it somewhere on their website.
If you put the NText column last in the SELECT list, you will be able to access it ok.
However, your code cannot access any other columns after it has read the NText value. Once you move to the next row of the recordset you're OK again.
Best solution is to change your connection string though, and use something more modern. That solves the problem in the best way!
To avoid using the recordset, try this:
For 1 record returned:
arr = rs.Getrows
if IsArray(arr) then
A = arr(0)
B = arr(1)
C = arr(2)
D = arr(3)
end if
For more records:
aryList = rec.GetRows
iCount = Ubound(aryList,2)
For i = 0 to iCount
A = aryList(0,i)
B = aryList(1,i)
C = aryList(2,i)
D = aryList(3,i)
' Do something with A,B,C,D
Next
casting ntext to varchar will do the job.
You're mixing unicode data (the ntext column) with non-unicode (varchar). That may be the reason, since the ASP page has to decide which to use.
Try and use either one or the other (casting non-unicode data to unicode may be the better option).
One extra tip for those who are working with older code:
When a recordset's column value is blank using ADO/ASP and you have a single line of data, you can bypass this problem by using a parameterised Command statement and returning the string value into a variable:
Some hand-typed code hopefully explains what I mean:
' DB connection
Set objCon = Server.CreateObject("ADODB.Connection")
objCon.CursorLocation = adUseClient
objCon.Open pubDbConnString
' statement construction
Set cmd = Server.CreateObject("ADODB.Command")
Set cmd.ActiveConnection = objCon
cmd.CommandText = "SELECT ?=T.Column1, ?=T.Column2 From Table T WHERE ID=?"
cmd.CommandType = adCmdText
' add parameters
cmd.Parameters.Append cmd.CreateParameter("#column1Data", adVarChar, adParamOutput, 8000)
cmd.Parameters.Append cmd.CreateParameter("#column2Data", adTinyInt, adParamOutput)
cmd.Parameters.Append cmd.CreateParameter("#id", adBigInt, adParamInput)
cmd.Parameters("#id").value = 1
set objRS = cmd.Execute
#column1Data will contain the large string. objRS will actually not have any records in it, so be mindful of this.
In theory, this should also work with named parameters with the same results, but I have not tested this.