XMLDocument I/O With DataTables And TableAdapters (final Version?)

May 25, 2006

The test sub below operates on a SQL Server Table  with an xml-type field ("xml").  The purpose of the sub is to learn about storing and retrieving a whole xml document as a single field in a SQL Server table row.

When the code saves to the xml field, it somehow automagically strips the xml.document.declaration (<?xml...>).  So when it reads the xml field back and tries to create an xmldocument from it, it halts at the xmldocument.load.

I order to  get the save/retrieve from the xmlfield to work, I add the <?xml declaration to
the string when I read it back in from the xml field (this is in the code below).

At that point the quickwatch on the string I'm attempting to load into the xmldocument is this:
-----------------------------------------------------
<?xml version="1.0" encoding="utf-16" ?><Control
type="TypeA"><Value1><SubVal1A>Units</SubVal1A><SubVal1B
type="TypeA">Type</SubVal1B></Value1><Value2><SubVal2A>Over</SubVal2A><SubVal2B>Load</SubVal2B>
</Value2></Control>
-----------------------------------------------------
The original xml document string is this:
-----------------------------------------------------
<?xml version="1.0" encoding="utf-16" ?>
<Control type="TypeA">
     <Value1>
          <SubVal1A>Units</SubVal1A>
          <SubVal1B type="TypeA">Type</SubVal1B>     
     </Value1>
     <Value2>
          <SubVal2A>Over</SubVal2A>
          <SubVal2B>Load</SubVal2B>
     </Value2>
</Control>
-----------------------------------------------------
which seems to have all the same characters as the quickwatch result above, but clearly is formatted differently because of the indenting.

THE FIRST QUESTION:  Is there a simpler way to do this whole thing using more appropriate methods that don't require adding the xml.document.declaration back in after reading the .xml field, or don't require using the memorystream to convert the .xml field in order to load it back to the XML document.

THE SECOND QUESTION:  Why does the original document open in the browser with "utf-16", but when I write the second document back to disk with "utf-16" it won't open...I have to change it to "utf-8" to open the second document in the browser.

Here's the test sub
'============================================
          
     Public Sub XMLDSTest()
          '===========================================
          Dim ColumnType As String = "XML"          

          '===========================================

          '----------Set up dataset, datatable, xmldocument

          Dim wrkDS As New DSet1()
          Dim wrkTable As New DSet1.Table1DataTable
          Dim wrkAdapter As New DSet1TableAdapters.Table1TableAdapter

          Dim wrkXDoc As New XmlDocument
          wrkXDoc.Load(SitePath & "App_XML" & "XMLFile.xml")

          Dim str1 = wrkXDoc.OuterXml
          Dim wrkRow As DSet1.Table1Row
          wrkRow = wrkTable.NewRow

          '=======WRITE to SQL Server==============
          '------ build new row
          With wrkRow
               Dim wrkG As Guid = System.Guid.NewGuid
               TestKey = wrkG.ToString
               .RecordKey = TestKey
               .xml = wrkXDoc.OuterXml     '<<< maps to SQL Server xml-type field
          End With

          '----- add row to table and update to disk
          wrkTable.Rows.Add(wrkRow)
          wrkAdapter.Update(wrkTable)
          wrkTable.AcceptChanges()
          '----- clear table
          wrkTable.Clear()

          '=======READ From SQL Server ==============
          '----refill table, read row,
          wrkAdapter.FillBy(wrkTable, TestKey)
          Dim wrkRow2 As DSet1.Table1Row = _
             wrkTable.Select("RecordKey = '" & TestKey & "'")(0)

          '=====  WRITE TO New .xml FILE ===========================
          Dim wrkS1 As New StringBuilder
          Select Case ColumnType
               Case "XML"
                    '---if xml build xml declaration:  
                    '---add this to xml from sql table   =>  <?xml version="1.0" encoding="utf-16" ?>
                    wrkS1.Append("<?xml version=" & Chr(34) & "1.0" & Chr(34))
                    wrkS1.Append(" encoding=" & Chr(34) & "utf-16" & Chr(34) & " ?>")
                    wrkS1.Append(wrkRow2.xml)
          End Select

          Dim wrkBytes As Byte() = (New UnicodeEncoding).GetBytes(wrkS1.ToString)
          Dim wrkXDoc2 As New XmlDocument
          Dim wrkStream As New MemoryStream(wrkBytes)
          wrkXDoc2.Load(wrkStream)
          '===========================================
          '---- this just shows that the file actually was touched
          Dim wrkN2 As XmlNode = wrkXDoc2.CreateNode(XmlNodeType.Text, "ss", "TestNode2")
          wrkN2 = wrkXDoc2.SelectSingleNode("//Value1/SubVal1B")
          wrkN2.Attributes("type").Value = "This was from the xml field"
          '----------------
          '------  update the encoding....otherwise the file won't open in the browser with utf-16
          Dim wrkN1 As XmlNode = wrkXDoc2.CreateNode(XmlNodeType.Element, "ss", "TestNode")
          wrkN1 = wrkXDoc2.FirstChild
          wrkN1.InnerText = Replace(wrkN1.InnerText, "utf-16", "utf-8")

          '------------Now write the file back as an .xml file
          Dim wrkFilePath As String = SitePath & "App_XML" & "XMLFile2.xml"
          Dim wrkXW As XmlWriter = XmlWriter.Create(wrkFilePath)
          wrkXDoc2.WriteContentTo(wrkXW)
          wrkXW.Close()

     End Sub



===============================

View 8 Replies


ADVERTISEMENT

Getting A Final Version Of A Person Into A DW

Feb 14, 2007

I have about 8 databases to integrate. All of the databases have ssno, address city...ect. I need to create a DW table with one unique record for each actual person. In other words,

Joe Smith,123 Main St, Anytown, State,....+ssno

goes into the DW table and is the same person as Joseph S. Smith,123 Main Street... and any other versions.

Could someone point me to a reference or give me an outline of how to do this in and SSIS package?

Is fuzzy logic used here?

Do I need to deduplicate the feeder systems first??

It needs to handle a situation in, for example, the Bronx New York where there could be an apartment buiding with 7 people named Jose Sanchez .

I hope I've been clear, I'm a newbie at this DW stuff, but it's fascinating. Any help would be appreciated. Thanks

View 1 Replies View Related

Release Of JDBC Driver 1.2 Final Version

Sep 12, 2007

Just wondering when the final (non-QA) version of the SQL Server 2005 driver is expected to be released.

Thanks.
Jeff

View 1 Replies View Related

What No XmlDocument...?

Jun 6, 2007

OK I am working on a SSIS package and am using a script task. I have to get remote xmldocuments from a server. Sounds simple enough. In C# it was easy but for some reason vb.net will not let me do this:

I can do a httpwebrequest and get the xml string into a variable strResponse

But the following will not work. The XmlDocument doesn't exists in the script task the vb code. On a side note I am importing Imports System.Xml in case anyone asks.


Dim doc As New XmlDocument
doc.LoadXml(strResponse)


Could anyone tell me how I would parse the xml elements using a script task?

here is the full code I am working with but all of the xml stuff has that blue squggly line underneathit.


Private Function ParseXmlIntoList(ByVal strResponse As String, ByVal l As List(Of StockInfo)) As List(Of StockInfo)

Dim doc As New XmlDocument

Try
doc.LoadXml(strResponse)
Catch
isError = True
Return l
End Try

Dim root As XmlElement = doc.DocumentElement
Dim list As XmlNodeList = root.SelectNodes("/StockData/Stock")

Dim x As Integer = 0

Dim n As XmlNode
For Each n In list
If l((x + intStartCount)).Symbol = getXMLElement(n, "Symbol") Then
l((x + intStartCount)).Price = Convert.ToDecimal(getXMLElement(n, "Last"))
l((x + intStartCount)).CompanyName = getXMLElement(n, "Name")
x += 1
Else

isError = True
Return l
End If
Next n

intStartCount = intStartCount + 25

Return l

End Function


Any help would be greatly appreciated.

Thanks,


JBelthoff
窶「 Hosts Station is a Professional Asp Hosting Provider
窶「 Position SEO can provide your company with SEO Services at an affordable price
窶コ As far as myself... I do this for fun!

View 1 Replies View Related

2005 Clr Returning Xmldocument

May 27, 2006

I would like to return an xmldocument from a 2005 vb clr stored procedure.

This is my definition for the stored procedure. passing in a string, return xmldoc.

Can I not return an xmldoc as output? The solution will build, but not run.



Partial Public Class StoredProcedures
<Microsoft.SqlServer.Server.SqlProcedure()> _
Public Sub SP_Transform(ByVal cc As String, <Out()> ByVal RetValue As XmlDocument)



Error 1 Column, parameter, or variable #2: Cannot find data type XmlDocument. SqlServerProject1

View 1 Replies View Related

SSIS Script - XmlDocument

Aug 10, 2007

This is all I have in SSIS Script Task


Imports System.Xml

Public Sub Main()
Dim doc As XmlDocument
doc.Load("C:Data est.xml")
Dts.TaskResult = Dts.Results.Success
End Sub

I get this error

Object reference not set to an instance of an object.

Any idea - Ashok

View 4 Replies View Related

TableAdapters

May 23, 2008

I moved from using data adapters to tableadapters. This is my sql query that is included in my data adapter

sql = "SELECT f.Date, CPT, CPTModifier, CPTModifier2, Description, Fee, Tax, Balance, [SPatient Number]
FROM Financial f
INNER JOIN Demographics d ON d.[Patient Number]=f.[SPatient Number] WHERE (f.[SPatient Number]= (" & intPID & "))"

conn.ConnectionString = My.Settings.EbtblsConnectionString
da = New SqlDataAdapter(sql, conn)

intPID is an input box that a user types a number in and compares it to SPatient Number on the Financial table. The query has been working fine.

However, when I go into designer view and hit the table adapter's "add query" property, in vs2008. I put that query in, and it gives me an error saying that intPID is not a valid column. I am aware it's not a valid column..because it isn't a column, it's a variable in the windows form. How do I put a variable in the sql string for table adapters?

View 2 Replies View Related

How Do I Store An XmlDocument In SQL Server 2005

Oct 23, 2006

Hi, I have  xmldocument type that stores xml data. I would like to able to store that data in sql server 2005 as a xml data type. How can I accomplish this using ado sqlcommand? XmlDocument xdoc = new XmlDocument();SqlConnection conn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Test"].ConnectionString);conn.Open();SqlCommand cmd = new SqlCommand(); cmd.Connection = conn;cmd.CommandType = CommandType.StoredProcedure;cmd.CommandText = "spStoreApp";cmd.Parameters.AddWithValue("@PersId", "222-22-2222");cmd.Parameters.AddWithValue("@AppData", xdoc);try{cmd.ExecuteNonQuery();Response.Write("Storage of application successful");}catch (SqlException sqlx){Response.Write(sqlx.Message);}conn.Close();thanks in advance.

View 3 Replies View Related

How Do I Load SQL Server XML Datatype Into XmlDocument In C#

Feb 22, 2007

Hi there,
How do i load a XML document saved in SQL server as a XML data type into
XmlDocument xdoc = new XmlDocument();xdoc.Load(// INTO HERE );
I can load a xml file saved to disk but haven't figured out how to retrive from a recordset. I have tried the following:
 
XmlDocument xdoc = new XmlDocument();xdoc.Load(GetXmlFile(pnrID).ToString());
 
public string GetXmlFile(int pnrID){
SqlConnection cnn = null;SqlCommand cmd = null;
string XML = "";
  try {
            cnn = new SqlConnection();            cnn.ConnectionString = "Server=;Initial Catalog=;UID=;PWD=;";            cnn.Open();
            string selectQry = "SELECT [XML] FROM [TEMP_PNR] WHERE PnrID = @PnrID";
            cmd = new SqlCommand(selectQry, cnn);
            cmd.Parameters.AddWithValue("@pnrID", pnrID);
            SqlDataReader rdr = cmd.ExecuteReader();
            if (rdr.Read())            XML = rdr.GetSqlXml(0).ToString();
        }
catch (Exception ex)           {            throw ex;            }
   finally {            cmd.Dispose();            cnn.Close();           }
return XML;
}
But this genereates the following error: Could not find file 'C:Program FilesMicrosoft Visual Studio 8Common7IDESystem.Data.SqlTypes.SqlXml'.
Any idea how i can achive this?

View 5 Replies View Related

Transaction+TableAdapters

May 14, 2007

Hi,
I have problem vith implementing Transaction with TableAdapters. My code is:
try
{
using (bookTableAdapter adapter = new bookTableAdapter())
{
transaction = TableAdapterHelper.BeginTransaction(adapter);
ID=(Guid) adapter.bookInsertNew(bookOrgId, bookISBN, bookName, Convert.ToInt32(bookYear), publisherId, languageId, orgLanguageId, bookTranslation, Convert.ToInt32(bookColors), Convert.ToInt32(bookPages), bookFormat, Convert.ToDouble(bookWidth), Convert.ToDouble(bookHeight), Convert.ToDouble(bookWeight), Convert.ToDouble(bookThickness), Convert.ToInt32(bookPrize), bookResumeText, bookResumeHtml, bookPicture_s, bookPicture_m, bookPicture_l, Convert.ToInt32(bookStatusId));
 
}
using (bookAuthorTableAdapter adapter1 = new bookAuthorTableAdapter())
{
TableAdapterHelper.SetTransaction(Adapter1, transaction);
 
for (int i = 0; i <= leng1; i++)
{
adapter1.Insert(author[i],ID,1);
 
}
}
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}finally
{
transaction.Dispose();
}
First Insert is ok, but trow exception on second try to insert in database.
Exceprion is :
Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.The statement has been terminated.Source Error:



Line 1839: }
Line 1840: try {
Line 1841: int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery();
Line 1842: return returnValue;
Line 1843: }
 I also set Connect Timeout=200 in Web.config but nothing change :(
Please help :( :( :(
 
 

View 1 Replies View Related

Should I Use TableAdapters Or DataAdapters For My DAL?

Feb 26, 2008

So I just created a very nice dataset class with 30+ tables and relationships for a very large project. Each table has 3-8 associated queries besides the usual Fill/Get and then there will be many more in the BLL that utilize this DAL.  I then created a BaseDAL class and other DAL classes that inherit from the BaseDAL(has basic sql query access if needed).  What I want to know is if the way I am doing this is correct and if this is a good idea for a database of this size.  I've never used TableAdapters before and I don't know if I should be using them at all?  I don't know how they handle connections and if one user will have more than one connection open because of using them or will they all share an open connection? 
 Can someone please direct me.  Thank you! Also, if you notice in the top of the UserDAL code I have listed below, I declare and initialize the usersTableAdapter and usersDeptTableAdapter.  Should the call to create the object be moved into each function?Public Class Users : Inherits BaseDAL
Private usersDS As OEE_USERSTableAdapter = New OEE_USERSTableAdapter()Private usersDeptDS As OEE_USER_DEPTSTableAdapter = New OEE_USER_DEPTSTableAdapter()Private retcode As Integer = 0
 
#Region "USER"
' Returns employee ID if user is in system, otherwise returns 0
Public Function ValidateUser(ByVal username As String) As String
'Dim usersDS As OEE_USERSTableAdapter = New OEE_USERSTableAdapter()Dim dtUser As New OEE_USERSDataTable
dtUser = usersDS.GetUser(username)
If dtUser.Rows.Count = 1 ThenReturn dtUser.Rows(0)("EMPLID").ToString
Else
Return "0"
End IfEnd Function
 
'Add User
Public Function InsertUser(ByVal emplid As String, ByVal username As String) As String
Dim insertedEmplid As String = ""
emplid = usersDS.AddUser(emplid, username)Return insertedEmplid
End Function
Public Function FlagAsInactive(ByVal emplid As String) As Boolean
retcode = usersDS.FlagAsInactive(emplid)Return retcode <> 0
End Function
'Sets inactive flag to null for user (Reactivates them)
Public Function ActivateUser(ByVal emplid As String) As Boolean
retcode = usersDS.ActivateUser(emplid)
Return True
End Function
'Returns list of all usersPublic Function GetUsers() As DataTable
Return usersDS.GetUsers
End Function
#End Region

View 2 Replies View Related

Combine Two Datatables

Mar 20, 2008

Hi,

I have a Excel file as data source. On sheet 1 there are some header information. On sheet 2 are a quiet simple data table. Both sheets will be read into memory with SSIS.

Now i want to combine some header information with the data table.

Sheet 1:
Unit A, 3/20/2008, Group 1

Sheet 2:
34ぎ, 56ぎ, 12ぎ
43ぎ, 43ぎ, 12ぎ
32ぎ, 42ぎ, 13ぎ
...

This should be result:
34ぎ, 56ぎ, 12ぎ, Unit A, 3/20/2008, Group1
43ぎ, 43ぎ, 12ぎ, Unit A, 3/20/2008, Group1
32ぎ, 42ぎ, 13ぎ, Unit A, 3/20/2008, Group1
...



How can I do this?


Regards
Johannes.W

View 3 Replies View Related

SQL Server 2005 And TableAdapters

Dec 11, 2006

Hello.  I have been using Table Adapters in VS2005 for the last several
projects and love them.  However, when I am connecting to a 2005 SQL
Server database, I have problems connecting.  That is, I cannot create
new stored procedures with the TableAdapter Config Wizard.  For
instance, I try to create a new query.  I use the wizard to create my
SQL statement and continue through until then end of the wizard, when
it asks me to "finish".  At this point, I get an error --  This only happens when trying to connect to a 2005 table.  Any ideas?  

View 1 Replies View Related

DB Null, Dates And Datatables

Jan 12, 2007

VS05
How are dates removed / nullified? 
I have a SQL datetime field that is being editted via a datatable / adapter - The table structure defines the datetime as a date.
From here I want to remove the date - i.e. write DBNull back to the database.  Setting the Date to Nothing or .minvalue results in a min date exception and DBNull cannot be cast to the datetime either.
R

View 3 Replies View Related

TableAdapters With Multiple Queries

Jul 18, 2007

Hello everyone...
I have created a report that pulls data from 5 different tables. I have created a tableadapter for this. I have a sql stored procedure with left joins that I am trying to use but keep getting key violations and not null value violations when I try to use it. I have tried setting the NULLValue to NOT throw exception but that has not helped. I have also tried to writing a query for each table. I can add each query to my tableadapter but I can use them all at the same time for some reason. Can this be done? When I go to my report and try to add fields to it from the tableadapter, I only see the results of one query. I am only trying to SELECT. I am not doing any updates or deletes to the tables on the SQL Server.
 Any advice would be greatly appreciated.

View 4 Replies View Related

TableAdapters And Custom SQL Statements

Nov 15, 2007

 
I've been working with TableAdapters, DAL, and BLL for a few months
now.  At this point, most of my new queries are too customized with
multiple tables to fit into any of my existing TableAdapter schema's. For
instance, if I want to execute an aggregate function with group by's
and counts that includes three separate tables, how would I go about
doing this with a strongly typed DAL using TableAdapters.  My
workaround to this point is to just create a whole new TableAdapter for
that one query.Is there anyway to extend the DAL in a strongly
typed dataset to create these "read-only" aggregate queries, or should
I continue to create new TableAdapters for each one of these queries?
 What's the proper way to handle such customized SQL statements that
don't fit any of my existing TableAdapters?

View 3 Replies View Related

Creating A VIEW With Multiple DATATABLES

Oct 24, 2007

I am still confounded with how to create a VIEW involving multiple DATATABLES in a DATASET.  Could someone point out a MSDN page where I can see this working and how I go about doing this?  Let me re-iterate - I want to create a VIEW that uses JOIN type statements that involves multiple DATATABLES in my loaded DATASET.

View 1 Replies View Related

Strongly Typed Datatables (out Of Resultsets)

Feb 18, 2008

I dragged two tables into the dataset designer. And I have a query with a resultset over both of the tables (joined).Is there ANY way I can have a strongly typed datatable out of the resultset?The automatically created dataset adapters won't allow me to create a tableadapter or datatable for the joined resultset but for one single table at a time only.Any solution to that? Theoretically it should be possible since I don't "lose" any type information with a join.. why can't I have a strongly typed datatable over the resultset?The join is not very sophisticated. In fact it couldn't be any more simple.(I'm refering to my previously posted question at http://forums.asp.net/t/1220481.aspx) 

View 4 Replies View Related

Public DataTables In Busines Object

Mar 21, 2007

Good Day:

I have a business object with a set of public DataTables and Public Strongly Typed Dataset DataTable Types defined. When I add the business object class to the report as a datasource, only public System datatypes (int, string) show up. I added System.Data to the report properties Assemblies, with no change. Any ideas?

Thanks,

Omar

View 1 Replies View Related

Crystal Reports .NET Using Several Related Datatables

Feb 1, 2008

Hi, I am new to Crystal Reports. I have a dataset with three datatables that are related. How can I do a subquery on these tables and display its result on my Crystal report ?

View 1 Replies View Related

Final Build?

Nov 16, 1998

Anyone know the final build # for the RTM version?

Thanks

View 2 Replies View Related

SP2 Final This Year ?

Dec 12, 2006

Does anyone know if the final SP2 will be out this year ?

Really need it for a production enviroment....

View 3 Replies View Related

Problem With Return Value Of Stored Procedure When Using Tableadapters

Dec 8, 2007

hello
Could you please help me with this problem?
I have a stored procedure like this:
ALTER PROCEDURE dbo.UniqueChannelName
(
@UserName nvarchar(50),
@ChannelName nvarchar(50)
)
AS
return 5;
 
Then inside of my dataset, I added a new query(dataset1.QueriesTableAdapter) to handle above mentioned stored procedure. Properties window is showing that return type of this adapter is of type int32 as we expected to be.
now I want to use it inside of my code:
DataSet1TableAdapters.QueriesTableAdapter b = new DataSet1TableAdapters.QueriesTableAdapter();
int i;
i=Convert.ToInt32( b.UniqueChannelName("Ahmad", "test"));
as you may guess, the return type of  b.UniqueChannelName("Ahmad", "test") is object and needs to be type-casted before assigning it's value to i; but even after explicit type casting, the value of i is always set to 0, not 5.
could you please show me the way?
many thanks in advance

View 19 Replies View Related

Final Part - Min() Function

May 23, 2006

I have the final part of my report to complete. Yesterday I posted the most confusing set of threads ever on a public forum. So to cut the confusion, I am starting this thread again as now I know exactly what I need.

I have two tables each of which have a function that gathers data from them based around a set of parameters. This is then manipulated by a third function and the results of which are passed into a Stored Procedure. Here is the T-SQL syntax used for the SP;

SELECT fnWTRalldataReport.Areacode, fnWTRalldataReport.siteref, fnWTRalldataReport.estatename, fnWTRalldataReport.Securitised,

fnWTRalldataReport.unitref, fnWTRalldataReport.unittype, fnWTRalldataReport.unittype_count, fnWTRalldataReport.tenantname,

fnWTRalldataReport.tenantstatus, fnWTRalldataReport.tenantstatus_count, fnWTRalldataReport.unitstatus, fnWTRalldataReport.unitstatus_count,

fnWTRalldataReport.floortotal, fnWTRalldataReport.floortotocc, fnWTRalldataReport.floorspaceperc, fnWTRalldataReport.initialvacarea,

fnWTRalldataReport.initialvacnet, fnWTRalldataReport.TotalRent, fnWTRalldataReport.NetRent, fnWTRalldataReport.FinalRtLsincSC,

fnWTRalldataReport.rentrolldiscperc, fnWTRalldataReport.netrentpersqft, fnWTRalldataReport.ErvTot, fnWTRalldataReport.tenancyterm,

fnWTRalldataReport.landact, fnWTRalldataReport.datadate, fnWTRalldataReport.div_mgr, fnWTRalldataReport.portfolio_mgr,

fnWTRalldataReport.propcat, fnWTRalldataReport.budgeted_net_rent, fnWTRalldataReport.budgeted_occupancy,

fnWTRbudgetdata_1.budgeted_net_rent AS budget_rent, fnWTRbudgetdata_1.budgeted_occupancy AS budget_occ

FROM dbo.fnWTRalldataReport(@dt_src_date, @chr_div, @vch_portfolio_no, @vch_prop_cat) AS fnWTRalldataReport LEFT OUTER JOIN

dbo.fnWTRbudgetdata(@dt_src_date) AS fnWTRbudgetdata_1 ON fnWTRalldataReport.siteref = fnWTRbudgetdata_1.site_ref

The result of this SQL places a value for budget_rent and budget_occ against every row that the 1st function's result set. What I want to achieve is that where the site_ref is equal in both functions results, I want it to place the budget_rent & budget_occ value against the first row only of each site_ref only.

To explain briefly the structure. Table one has various fields including site_ref and unit_ref. There are many unit_ref's per site_ref in this table. Table 2 has only site_ref and budget info. Someone yesterday suggested that I could achieve this my using something along the lines of the Min() function e.g. Min(unit_ref).

Could someone please elaborate on this for me. I have gone through my SQL book and read about min() and also BOL, but I can't quite work the syntax out to put the budget info against only one line per site based around the lowest unit_ref per site_ref.

This might seem confusing, but it is easier to read than the other thread I assure you.

Regards

View 3 Replies View Related

DataTables In SQLExpress Database Are Not Updating When Using Stored Procedures From Windows Application

Jan 30, 2008

I'm writing a Windows application (Visual Studio 2005, c#) utilizing a local SQLExpress database. It consists of about 10 tables and I've created about 15 Stored Procedures to address various functions... I can run the update Stored Procedures interactively within the designer and the data tables update as designed. However, if I run the update Stored Procedures from within my windows application is where they fail. I get no error messages, if I return a rowcount variable from the Stored Procedure it tells me that one row was updated (SELECT @RtnVal == @@rowcount)... but when I open the subject table in the designer, there is no new data.

My update queries address both insert and update functions, so if it is new row of data, it performs the insert action, otherwise it updates an existing row.

I can query the data using my stored procedures to load default values into my windows form, I can search and find client records to display in the form... I just can't update records. I'm of the opinion that it is a rights issue, but I can't find any resources that address user access accounts with SQLExpress and windows apps. The current connection string for my local database is set for Integrated Security = true; User Instance = true

I've tried two approaches... one utilizes my stored procedure....


bool bSave;
SqlConnection conn = new SqlConnection(KadaDesk.Properties.Settings.Default.dbKadaConnectionString.ToString());
SqlCommand cmd = new SqlCommand("SavAuthTesterData", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@CtrId", SqlDbType.NVarChar, 20).Value = TestCenterID.ToString();
cmd.Parameters.Add("@AT_Id", SqlDbType.NVarChar, 15).Value = GnuAuthTesterId.ToString();
cmd.Parameters.Add("@AT_Name", SqlDbType.NVarChar, 50).Value = GnuAuthTesterName.ToString();
cmd.Parameters.Add("@AT_Pwd", SqlDbType.NVarChar, 15).Value = GnuAuthTesterPwd.ToString();
cmd.Parameters.Add("@Maint", SqlDbType.NChar, 1).Value = GnuAuthTesterStatus.ToString();
cmd.Parameters.Add("@ModBy", SqlDbType.NVarChar, 15).Value = sAuthTester.ToString();
try
{
conn.Open();
cmd.ExecuteNonQuery();
bSave = true;
}

Then I tried a direct insert...

SqlConnection conn = new SqlConnection(KadaDesk.Properties.Settings.Default.dbKadaConnectionString.ToString());
SqlCommand cmd = new SqlCommand();
SqlTransaction myTrans;
conn.Open();
cmd.Connection = conn;
myTrans = conn.BeginTransaction();
cmd.Transaction = myTrans;
string disDte = DateTime.Now.ToShortDateString();
try
{
string sCmdText = "INSERT INTO Tester (CenterId, AuthTesterId, AuthTesterName, AuthTesterPwd, "
+ "CreateDte, Maint, ModBy) "
+ "VALUES ('" + TestCenterID.ToString() + "','"
+ GnuAuthTesterId.ToString() + "','"
+ GnuAuthTesterName.ToString() + "','"
+ GnuAuthTesterPwd.ToString() + "','"
+ disDte.ToString() + "','"
+ GnuAuthTesterStatus.ToString() + "','"
+ sAuthTester.ToString() + "')";
cmd.CommandText = sCmdText;
cmd.ExecuteNonQuery();
myTrans.Commit();
bSave = true;
}


Both fail... which points to the only common point in both approaches, the connection string and user rights... but I can't find any place to address user accounts or configurations for windows apps.

Thanks for whatever help you can offer...

Jim-

View 5 Replies View Related

Final Attemp -Sql Stored Procedure Tough Question

Mar 17, 2004

I have a procedure I need to get the values out of..I am using outputs...I have no idea why it wont work......I need all values listed in the select part of procedure....



CREATE procedure dbo.Appt_Login_NET
(
@LoginName nvarchar(15),
@Password NvarChar(15),
@UserName nvarchar(15)Output,
@UserPassword nvarchar(15)Output,
@UserClinic nvarchar(3)Output,
@UserTester bit Output
)
as
select
UserName,
UserPassword,
UserClinic,
UserTester
from
Clinic_users
where
UserName = @LoginName
and
UserPassword = @Password

GO



my vb.net code to retrive this info is

Private Sub Button1_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.ServerClick
Dim con As New SqlConnection("Server=myserver;database=APPOINTMENTS;uid=webtest;pwd=webtest")
Dim cmd As New SqlCommand
Dim parmuser As SqlParameter
Dim parmus As SqlParameter
Dim parmpass As SqlParameter
Dim parmtest As SqlParameter
Dim struser As String
Dim strpass As String
Dim strclinic As String
Dim strnames As String
Dim tester As String
strpass = txtPass.Value
struser = txtUser.Value
cmd = New SqlCommand("Appt_Login_NET", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@LoginName", struser)
cmd.Parameters.Add("@Password", strpass)
parmus = cmd.Parameters.Add("@UserName", SqlDbType.NVarChar)
parmus.Size = 15
parmus.Direction = ParameterDirection.Output
parmuser = cmd.Parameters.Add("@UserClinic", SqlDbType.NVarChar)
parmuser.Size = 3
parmuser.Direction = ParameterDirection.Output
parmpass = cmd.Parameters.Add("@UserPassword", SqlDbType.NVarChar)
parmpass.Size = 15
parmpass.Direction = ParameterDirection.Output
parmtest = cmd.Parameters.Add("@UserTester", SqlDbType.Bit)
parmtest.Size = 1
parmtest.Direction = ParameterDirection.Output

con.Open()
cmd.ExecuteNonQuery()
If Not IsDBNull(cmd.Parameters("@UserName").Value) Then
Label1.Text = cmd.Parameters("@UserName").Value()
Else
Label1.Text = "No Results Found"
End If

con.Close()
End Sub

Why does this always show as "DBNUll" I get nothing when I debug any of my parm variables.I searched the SQl Server and in Query analyzer instead of the output variables in the procedure being just outputs they are input/outputs...................What does it take to get this working??? Do I need a conversion datatype I would prefer I gain the values and store them in variables......

View 7 Replies View Related

Update Final Table With Values Into Comma Separator?

Mar 24, 2014

I would like to update the final table with values into a comma separator as follows with examples:

I think I have the IDs set correctly for this example:

You can see from the final table that the code column can be a combination of more than one rows from the map tables...

create table #tblTax(TaxStatusID int, FullName varchar(20)
insert into #tblTax values(1, 'Taxable')
insert into #tblTax values(2, 'exempt')

create table #tblTypes(TypeID int, description varchar(100)
insert into #tblTypes values(1, 'cor')
insert into #tblTypes values(2, 'tyr')

[code]....

Looking at the above example, I would like to have the #tblMain as follows

#tblMain
ShoetNameLongNameClientNameTaxIDTypeID
======================================================================
A, B'dand, Barlow''johnson'133
G'mond''anderson'26
I'somelongcode''jacksons'21
A, B'dand, Barlow''smith'112

View 2 Replies View Related

SQL Server 2008 :: Pivot Function - Additional Final Column

Mar 11, 2015

I've managed to use the pivot function using the code below which gives me the following output:

Location_Code Gt 0-1 Gt 1-2 Gt 2-3 Gt 3-4
North 10 0 3 5
West 6 3 2 0
South 4 2 8 2

This is exactly what I want but I would like an additional final column that will total the columns by location_code and weekband.

[Location_Code] AS 'Location Code'
,[Gt 0-1], [Gt 1-2], [Gt 2-3], [Gt 3-4]
from (select [WeekBand]
,[Location_Code]
, count(*) as CountOf

[Code] ....

View 7 Replies View Related

Call Stored Procedure For Last 4 Months Then Combine Into Final Result Set Row

May 3, 2006

I want to call my stored proc for that last 4 months. Basically all I need to do is pass each month's first date and it will do the rest. Should I shove this into a UDF first? I'm not sure if I can do that. The struction is here behind my stored proc: http://www.webfound.net/storedproc.txt

EXEC IT_Get_Dashboard_Monthly '2006-05-03 12:03:43.910' <-- change to UDF or leave it? Then how can I loop and change each month to cover the last 4 months?

I also need to ensure all 4 values returned in each interation show up in one row in the final result set that is produced

View 1 Replies View Related

SQL Server Admin 2014 :: Restore A Database Of Higher Version To Lower Version?

Sep 1, 2014

Is there any way to restore a database of higher version to lower version.

E.g. I have created a database in sql server 2012, created some tables & procedures in that.I took Full backup of that database. Can I restore it to sql 2008r2 or any lower version.

I know direct restore is not possible, I have to use either import or export option or generating script,but i want to know is there any easy step to do so.

Vimal Lohani
SQL DBA | MCP (70-461,70-462)

View 4 Replies View Related

Can I Install A Enterprise Version Analysis Service On A Standard Version Of SQL 2005 Server?

Jul 25, 2006

Hi all,

Since some analysis services features are only available in Enterprise version , I have to upgrade my SQL 2005 server from standard edition to enterpise edition.

So I uninstall originial standard version of analysis service and install a Enterprise version. However, the analysis service is still a standard version after installation.

Is it possible to keep data engine as standard version and install a enterprise version of analysis service?

Thank you very much

Tony

View 1 Replies View Related

What Sql Server Version To Buy? Difference In Performance Between The Workgroup And Standard Version

Feb 19, 2008

Hello,I have been searching and reading a lots of information on the microsoft  website about the different version of SQL server, but still can not make my decision.In term of performance, is there a real big difference between the workgroup and the standard version? The workgroup is limited to 3 GB of RAM while the standard is unlimited, would that really change the performance if my server has 16Gb or RAM?The price difference is pretty substantial so if could only have to buy the workgroup , it would be better.One more question, regarding the type of licence, my server has 2 processors, could I avoid buying 2 licences and get the Server plus CAL instead. I am using this server to host 4 web-application running on SQL server. Each database is about 15 MB.Thanks in adavance for your advises.Arno

View 3 Replies View Related

Changing From SQL Server Enterprise Evaluation Version To Developer Version

Oct 30, 2007

I am wondering if it is possible to change from SQL Server Enterprise Evaluation Version to Developer Version. The reason is because the Enterprise Evaluation version expires after 180 days. So if I create reports and cubes in Enterprise Evaluation I can import them into Developer Edition right? Should I remove the Enterprise Evaluation version after 180 days or leave it then install Developer Edition?

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved