Search Results

Search found 131 results on 6 pages for 'sproc'.

Page 3/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • How do I iterate through hierarchical data in a Sql Server 2005 stored proc?

    - by AlexChilcott
    Hi, I have a SqlServer2005 table "Group" similar to the following: Id (PK, int) Name (varchar(50)) ParentId (int) where ParentId refers to another Id in the Group table. This is used to model hierarchical groups such as: Group 1 (id = 1, parentid = null) +--Group 2 (id = 2, parentid = 1) +--Group 3 (id = 3, parentid = 1) +--Group 4 (id = 4, parentid = 3) Group 5 (id = 5, parentid = null) +--Group 6 (id = 6, parentid = 5) You get the picture I have another table, let's call it "Data" for the sake of simplification, which looks something like: Id (PK, int) Key (varchar) Value (varchar) GroupId (FK, int) Now, I am trying to write a stored proc which can get me the "Data" for a given group. For example, if I query for group 1, it returns me the Key-Value-Pairs from Data where groupId = 1. If I query for group 2, it returns the KVPs for groupId = 1, then unioned with those which have groupId = 2 (and duplicated keys are replaced). Ideally, the sproc would also fail gracefully if there is a cycle (ie if group 1's parent is group 2 and group 2's parent is group 1) Has anyone had experience in writing such a sproc, or know how this might be accomplished? Thanks guys, much appreciated, Alex

    Read the article

  • SQL03070: This statement is not recognized in this context

    - by prash
    Recently I have started working with VS2010 and Fx4. There have been various challenges. We also introduced a new Database Project in our solution. And found this error. The reason for this error is: the project system expects the stored procedure as a create statement only.  The additional statements to drop if existing are not necessary within the project system.  Project deployment takes care of detecting if the sproc already exists and if it needs to be updated. To resolve this error you can simply remove the additional statements other then your create SP, Function etc. OR Exclude the file from build. Right Click on your file in Solution Explorer, Click Properties > Build Action > Not in Build

    Read the article

  • SQL Table stored as a Heap - the dangers within

    - by MikeD
    Nearly all of the time I create a table, I include a primary key, and often that PK is implemented as a clustered index. Those two don't always have to go together, but in my world they almost always do. On a recent project, I was working on a data warehouse and a set of SSIS packages to import data from an OLTP database into my data warehouse. The data I was importing from the business database into the warehouse was mostly new rows, sometimes updates to existing rows, and sometimes deletes. I decided to use the MERGE statement to implement the insert, update or delete in the data warehouse, I found it quite performant to have a stored procedure that extracted all the new, updated, and deleted rows from the source database and dump it into a working table in my data warehouse, then run a stored proc in the warehouse that was the MERGE statement that took the rows from the working table and updated the real fact table. Use Warehouse CREATE TABLE Integration.MergePolicy (PolicyId int, PolicyTypeKey int, Premium money, Deductible money, EffectiveDate date, Operation varchar(5)) CREATE TABLE fact.Policy (PolicyKey int identity primary key, PolicyId int, PolicyTypeKey int, Premium money, Deductible money, EffectiveDate date) CREATE PROC Integration.MergePolicy as begin begin tran Merge fact.Policy as tgtUsing Integration.MergePolicy as SrcOn (tgt.PolicyId = Src.PolicyId) When not matched by Target then Insert (PolicyId, PolicyTypeKey, Premium, Deductible, EffectiveDate)values (src.PolicyId, src.PolicyTypeKey, src.Premium, src.Deductible, src.EffectiveDate) When matched and src.Operation = 'U' then Update set PolicyTypeKey = src.PolicyTypeKey,Premium = src.Premium,Deductible = src.Deductible,EffectiveDate = src.EffectiveDate When matched and src.Operation = 'D' then Delete ;delete from Integration.WorkPolicy commit end Notice that my worktable (Integration.MergePolicy) doesn't have any primary key or clustered index. I didn't think this would be a problem, since it was relatively small table and was empty after each time I ran the stored proc. For one of the work tables, during the initial loads of the warehouse, it was getting about 1.5 million rows inserted, processed, then deleted. Also, because of a bug in the extraction process, the same 1.5 million rows (plus a few hundred more each time) was getting inserted, processed, and deleted. This was being sone on a fairly hefty server that was otherwise unused, and no one was paying any attention to the time it was taking. This week I received a backup of this database and loaded it on my laptop to troubleshoot the problem, and of course it took a good ten minutes or more to run the process. However, what seemed strange to me was that after I fixed the problem and happened to run the merge sproc when the work table was completely empty, it still took almost ten minutes to complete. I immediately looked back at the MERGE statement to see if I had some sort of outer join that meant it would be scanning the target table (which had about 2 million rows in it), then turned on the execution plan output to see what was happening under the hood. Running the stored procedure again took a long time, and the plan output didn't show me much - 55% on the MERGE statement, and 45% on the DELETE statement, and table scans on the work table in both places. I was surprised at the relative cost of the DELETE statement, because there were really 0 rows to delete, but I was expecting to see the table scans. (I was beginning now to suspect that my problem was because the work table was being stored as a heap.) Then I turned on STATS_IO and ran the sproc again. The output was quite interesting.Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.Table 'Policy'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.Table 'MergePolicy'. Scan count 1, logical reads 433276, physical reads 60, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. I've reproduced the above from memory, the details aren't exact, but the essential bit was the very high number of logical reads on the table stored as a heap. Even just doing a SELECT Count(*) from Integration.MergePolicy incurred that sort of output, even though the result was always 0. I suppose I should research more on the allocation and deallocation of pages to tables stored as a heap, but I haven't, and my original assumption that a table stored as a heap with no rows would only need to read one page to answer any query was definitely proven wrong. It's likely that some sort of physical defragmentation of the table may have cleaned that up, but it seemed that the easiest answer was to put a clustered index on the table. After doing so, the execution plan showed a cluster index scan, and the IO stats showed only a single page read. (I aborted my first attempt at adding a clustered index on the table because it was taking too long - instead I ran TRUNCATE TABLE Integration.MergePolicy first and added the clustered index, both of which took very little time). I suspect I may not have noticed this if I had used TRUNCATE TABLE Integration.MergePolicy instead of DELETE FROM Integration.MergePolicy, since I'm guessing that the truncate operation does some rather quick releasing of pages allocated to the heap table. In the future, I will likely be much more careful to have a clustered index on every table I use, even the working tables. Mike  

    Read the article

  • SubSonic 2.x now supports TVP's - SqlDbType.Structure / DataTables for SQL Server 2008

    - by ElHaix
    For those interested, I have now modified the SubSonic 2.x code to recognize and support DataTable parameter types. You can read more about SQL Server 2008 features here: http://download.microsoft.com/download/4/9/0/4906f81b-eb1a-49c3-bb05-ff3bcbb5d5ae/SQL%20SERVER%202008-RDBMS/T-SQL%20Enhancements%20with%20SQL%20Server%202008%20-%20Praveen%20Srivatsav.pdf What this enhancement will now allow you to do is to create a partial StoredProcedures.cs class, with a method that overrides the stored procedure wrapper method. A bit about good form: My DAL has no direct table access, and my DB only has execute permissions for that user to my sprocs. As such, SubSonic only generates the AllStructs and StoredProcedures classes. The SPROC: ALTER PROCEDURE [dbo].[testInsertToTestTVP] @UserDetails TestTVP READONLY, @Result INT OUT AS BEGIN SET NOCOUNT ON; SET @Result = -1 --SET IDENTITY_INSERT [dbo].[tbl_TestTVP] ON INSERT INTO [dbo].[tbl_TestTVP] ( [GroupInsertID], [FirstName], [LastName] ) SELECT [GroupInsertID], [FirstName], [LastName] FROM @UserDetails IF @@ROWCOUNT > 0 BEGIN SET @Result = 1 SELECT @Result RETURN @Result END --SET IDENTITY_INSERT [dbo].[tbl_TestTVP] OFF END The TVP: CREATE TYPE [dbo].[TestTVP] AS TABLE( [GroupInsertID] [varchar](50) NOT NULL, [FirstName] [varchar](50) NOT NULL, [LastName] [varchar](50) NOT NULL ) GO The the auto gen tool runs, it creates the following erroneous method: /// <summary> /// Creates an object wrapper for the testInsertToTestTVP Procedure /// </summary> public static StoredProcedure TestInsertToTestTVP(string UserDetails, int? Result) { SubSonic.StoredProcedure sp = new SubSonic.StoredProcedure("testInsertToTestTVP", DataService.GetInstance("MyDAL"), "dbo"); sp.Command.AddParameter("@UserDetails", UserDetails, DbType.AnsiString, null, null); sp.Command.AddOutputParameter("@Result", DbType.Int32, 0, 10); return sp; } It sets UserDetails as type string. As it's good form to have two folders for a SubSonic DAL - Custom and Generated, I created a StoredProcedures.cs partial class in Custom that looks like this: /// <summary> /// Creates an object wrapper for the testInsertToTestTVP Procedure /// </summary> public static StoredProcedure TestInsertToTestTVP(DataTable dt, int? Result) { DataSet ds = new DataSet(); SubSonic.StoredProcedure sp = new SubSonic.StoredProcedure("testInsertToTestTVP", DataService.GetInstance("MyDAL"), "dbo"); // TODO: Modify the SubSonic code base in sp.Command.AddParameter to accept // a parameter type of System.Data.SqlDbType.Structured, as it currently only accepts // System.Data.DbType. //sp.Command.AddParameter("@UserDetails", dt, System.Data.SqlDbType.Structured null, null); sp.Command.AddParameter("@UserDetails", dt, SqlDbType.Structured); sp.Command.AddOutputParameter("@Result", DbType.Int32, 0, 10); return sp; } As you can see, the method signature now contains a DataTable, and with my modification to the SubSonic framework, this now works perfectly. I'm wondering if the SubSonic guys can modify the auto-gen to recognize a TVP in a sproc signature, as to avoid having to re-write the warpper? Does SubSonic 3.x support Structured data types? Also, I'm sure many will be interested in using this code, so where can I upload the new code? Thanks.

    Read the article

  • Distributed Transactions in SQL Server 2005

    - by AJM
    As part of a transaction I’m modifying rows in tables via a server link, so have to specify “SET XACT_ABORT ON” in my sproc otherwise it won’t execute. Now I’m noticing that SCOPE_IDENTITY() is returning NULL, which is presumably something to do with the distributed transaction scope? Does anyone know why and how to resolve?

    Read the article

  • How to send hashed data in SOAP request body?

    - by understack
    I want to imitate following request using Zend_Soap_Client for this wsdl. <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <SOAP-ENV:Header> <h3:__MethodSignature xsi:type="SOAP-ENC:methodSignature" xmlns:h3="http://schemas.microsoft.com/clr/soap/messageProperties" SOAP-ENC:root="1" xmlns:a2="http://schemas.microsoft.com/clr/ns/System.Collections">xsd:string a2:Hashtable</h3:__MethodSignature> </SOAP-ENV:Header> <SOAP-ENV:Body> <i4:ReturnDataSet id="ref-1" xmlns:i4="http://schemas.microsoft.com/clr/nsassem/Interface.IRptSchedule/Interface"> <sProc id="ref-5">BU</sProc> <ht href="#ref-6"/> </i4:ReturnDataSet><br/> <a2:Hashtable id="ref-6" xmlns:a2="http://schemas.microsoft.com/clr/ns/System.Collections"> <LoadFactor>0.72</LoadFactor> <Version>1</Version> <Comparer xsi:null="1"/> <HashCodeProvider xsi:null="1"/> <HashSize>11</HashSize> <Keys href="#ref-7"/> <Values href="#ref-8"/> </a2:Hashtable> <SOAP-ENC:Array id="ref-7" SOAP-ENC:arrayType="xsd:anyType[1]"> <item id="ref-9" xsi:type="SOAP-ENC:string">@AppName</item> </SOAP-ENC:Array><br/> <SOAP-ENC:Array id="ref-8" SOAP-ENC:arrayType="xsd:anyType[1]"> <item id="ref-10" xsi:type="SOAP-ENC:string">AAGENT</item> </SOAP-ENC:Array> </SOAP-ENV:Body> </SOAP-ENV:Envelope> It seems somehow I've to send hashed "ref-7" and "ref-8" array embedded inside body? How can I do this? Function ReturnDataSet takes two parameters, how can I send additional "ref-7" and "ref-8" array data? $client = new SoapClient($wsdl_url, array('soap_version' => SOAP_1_1)); $result = $client->ReturnDataset("BU", $ht); I don't know how to set $ht, so that hashed data is sent as different body entry. Thanks.

    Read the article

  • How do I convert int? into int

    - by Richard77
    Hello, I've create a SPROC that saves an object and returns the id of the new object saved. Now, I'd like to return an int not an int? public int Save(Contact contact) { int? id; context.Save_And_SendBackID(contact.FirstName, contact.LastName, ref id); //How do I return an int instead of an int? } Thanks for helping

    Read the article

  • CTE Join query issues

    - by Lee_McIntosh
    Hi everyone, this problem has me head going round in circles at the moment and i wondering if anyone could give any pointers as to where im going wrong. Im trying to produce a SPROC that produces a dataset to be called by SSRS for graphs spanning the last 6 months. The data for example purposes uses three tables (theres more but the it wont change the issue at hand) and are as follows: tbl_ReportList: Report Site ---------------- North abc North def East bbb East ccc East ddd South poa South pob South poc South pod West xyz tbl_TicketsRaisedThisMonth: Date Site Type NoOfTickets --------------------------------------------------------- 2010-07-01 00:00:00.000 abc Support 101 2010-07-01 00:00:00.000 abc Complaint 21 2010-07-01 00:00:00.000 def Support 6 ... 2010-12-01 00:00:00.000 abc Support 93 2010-12-01 00:00:00.000 xyz Support 5 tbl_FeedBackRequests: Date Site NoOfFeedBackR ---------------------------------------------------------------- 2010-07-01 00:00:00.000 abc 101 2010-07-01 00:00:00.000 def 11 ... 2010-12-01 00:00:00.000 abc 63 2010-12-01 00:00:00.000 xyz 4 I'm using CTE's to simplify the code, which is as follows: DECLARE @ReportName VarChar(200) SET @ReportName = 'North'; WITH TicketsRaisedThisMonth AS ( SELECT [Date], Site, SUM(NoOfTickets) AS NoOfTickets FROM tbl_TicketsRaisedThisMonth WHERE [Date] >= DATEADD(mm, DATEDIFF(m,0,GETDATE())-6,0) GROUP BY [Date], Site ), FeedBackRequests AS ( SELECT [Date], Site, SUM(NoOfFeedBackR) AS NoOfFeedBackR FROM tbl_FeedBackRequests WHERE [Date] >= DATEADD(mm, DATEDIFF(m,0,GETDATE())-6,0) GROUP BY [Date], Site ), SELECT trtm.[Date] SUM(trtm.NoOfTickets) AS NoOfTickets, SUM(fbr.NoOfFeedBackR) AS NoOfFeedBackR, FROM Reports rpts LEFT OUTER JOIN TotalIncidentsDuringMonth trtm ON rpts.Site = trtm.Site LEFT OUTER JOIN LoggedComplaints fbr ON rpts.Site = fbr.Site WHERE rpts.report = @ReportName GROUP BY trtm.[Date] And the output when the sproc is pass a parameter such as 'North' to be as follows: Date NoOfTickets NoOfFeedBackR ----------------------------------------------------------------------------------- 2010-07-01 00:00:00.000 128 112 2010-08-01 00:00:00.000 <data for that month> <data for that month> 2010-09-01 00:00:00.000 <data for that month> <data for that month> 2010-10-01 00:00:00.000 <data for that month> <data for that month> 2010-11-01 00:00:00.000 <data for that month> <data for that month> 2010-12-01 00:00:00.000 122 63 The issue I'm having is that when i execute the query I'm given a repeated list of values of each month, such as 128 will repeat 6 times then another value for the next months value repeated 6 times, etc. argh!

    Read the article

  • T-SQL Hierarchy to duplicate Dependent Objects tree view in SQL Server 2005

    - by drewg
    Hi Id like to map the calling stack from one master stored procedure through its hundreds of siblings. i can see it in the dialog, but cannot copy or print it, but couldnt trap anythiing worthwhile in proflier. do you know what sproc fills that treeview? i must be a recursive CTE that reads syscomments or information_schema.routines, but its beyond my chops, though i can imagine it thanks in advance drew

    Read the article

  • vb6 ADODB TSQL procedure call quit working after database migration

    - by phill
    This code was once working on sql server 2005. Now isolated in a visual basic 6 sub routine using ADODB to connect to a sql server 2008 database it throws an error saying: "Login failed for user 'admin' " I have since verified the connection string does work if i replace the body of this sub with the alternative code below this sub. When I run the small program with the button, it stops where it is marked below the asterisk line. Any ideas? thanks in advance. Private Sub Command1_Click() Dim cSQLConn As New ADODB.Connection Dim cmdGetInvoices As New ADODB.Command Dim myRs As New ADODB.Recordset Dim dStartDateIn As Date dStartDateIn = "2010/05/01" cSQLConn.ConnectionString = "Provider=sqloledb;" _ & "SERVER=NET-BRAIN;" _ & "Database=DB_app;" _ & "User Id=admin;" _ & "Password=mudslinger;" cSQLConn.Open cmdGetInvoices.CommandTimeout = 0 sProc = "GetUnconvertedInvoices" 'On Error GoTo GetUnconvertedInvoices_Err With cmdGetInvoices .CommandType = adCmdStoredProc .CommandText = "_sp_cwm5_GetUnCvtdInv" .Name = "_sp_cwm5_GetUnCvtdInv" Set oParm1 = .CreateParameter("@StartDate", adDate, adParamInput) .Parameters.Append oParm1 oParm1.Value = dStartDateIn .ActiveConnection = cSQLConn End With With myRs .CursorLocation = adUseClient .LockType = adLockBatchOptimistic .CursorType = adOpenKeyset '.CursorType = adOpenStatic .CacheSize = 5000 '***************************Debug stops here .Open cmdGetInvoices End With If myRs.State = adStateOpen Then Set GetUnconvertedInvoices = myRs Else Set GetUnconvertedInvoices = Nothing End If End Sub Here is the code which validates the connection string is working. Dim cSQLConn As New ADODB.Connection Dim cmdGetInvoices As New ADODB.Command Dim myRs As New ADODB.Recordset cSQLConn.ConnectionString = "Provider=sqloledb;" _ & "SERVER=NET-BRAIN;" _ & "Database=DB_app;" _ & "User Id=admin;" _ & "Password=mudslinger;" cSQLConn.Open cmdGetInvoices.CommandTimeout = 0 sProc = "GetUnconvertedInvoices" With cmdGetInvoices .ActiveConnection = cSQLConn .CommandText = "SELECT top 5 * FROM tarInvoice;" .CommandType = adCmdText End With With myRs .CursorLocation = adUseClient .LockType = adLockBatchOptimistic '.CursorType = adOpenKeyset .CursorType = adOpenStatic '.CacheSize = 5000 .Open cmdGetInvoices End With If myRs.EOF = False Then myRs.MoveFirst Do MsgBox "Record " & myRs.AbsolutePosition & " " & _ myRs.Fields(0).Name & "=" & myRs.Fields(0) & " " & _ myRs.Fields(1).Name & "=" & myRs.Fields(1) myRs.MoveNext Loop Until myRs.EOF = True End If

    Read the article

  • Convert dependencies to point to View instead of Table

    - by jwarzech
    I currently have a SQL Server 2008 database in which I am planning to separate out some tables to other databases. I want to be able to replace all references to the separated tables from the original database using views. Is there a better way (other than manually changing all FK and SProc references) to switch all the dependencies to reference the view instead of the table?

    Read the article

  • How to save a Stored Procedure ?

    - by Richard77
    Hello, I've been playing today with stored procedures. I'm stoned that I picked the basic of it up so easily. (I'll also try triggers very soon). Now, I'd like to know how to save my SPROC under the stored procedure folder (Programmability - Stored Procedure) so that I can access it by name (eventually from my C# application). So far, when I press the save icon, I'm proposed to save the whole query. That's not what I want. Thanks for helping

    Read the article

  • Oracle parameter array binding from c# executed parallel and serial on different servers

    - by redir_dev_nut
    I have two Oracle 9i 64 bit servers, dev and prod. Calling a procedure from a c# app with parameter array binding, prod executes the procedure simultaneously for each value in the parameter array, but dev executes for each value serially. So, if the sproc does: select count(*) into cnt from mytable where id = 123; if cnt = 0 then insert into mytable (id) values (123); end if; Assuming the table initially does not have an id = 123 row. Dev gets cnt = 0 for the first array parameter value, then 1 for each of the subsequent. Prod gets cnt = 0 for all array parameter values and inserts id 123 for each. Is this a configuration difference, an illusion due to speed difference, something else?

    Read the article

  • Cool SQL formatter tool

    - by AndyScott
    I have to deal with all types of code that was written by people from different organizations, different countries, using different languages, obviously standards are different across these sources.  One of the biggest headaches that I ahve come across is how people differ in the formatting of their SQL statements, specifically stored procs.  When you regularly get over 500 lines in a sproc, if the code is not formatted correctly, you can get lost trying to figure out where one nested BEGIN begins, and another nested END ends.  One of my co-workers showed me this site today that does a pretty damn good job of making sense of that type of code: http://www.dpriver.com/pp/sqlformat.htm.   This is a free website that offers a box to enter your nasty code, and click "Format SQL" and have it clean it for you.  I am sure that there are situations where this may not work, but given the code that I have been working with recently, it does a really good job.  There is a pay version with more options, including VS add-in, desktop component (with quickkeys to clean text in programs like notepad), the ability to output in HTML, and other stuff.  Heck, I watched a demo where the purchased version will take formatted SQL code and turn it into a generic Stringbuilder object embedded in a formatted. Yes, this seems like a shameless plug, but no, I have no relation/knowledge of anyone involved in the development of this product, it just seems useful.  Either way, I recommend checking out the free version.

    Read the article

  • Sending changes from multiple tables in disconnected dataset to SQLServer...

    - by Stecy
    We have a third party application that accept calls using an XML RPC mechanism for calling stored procs. We send a ZIP-compressed dataset containing multiple tables with a bunch of update/delete/insert using this mechanism. On the other end, a CLR sproc decompress the data and gets the dataset. Then, the following code gets executed: using (var conn = new SqlConnection("context connection=true")) { if (conn.State == ConnectionState.Closed) conn.Open(); try { foreach (DataTable table in ds.Tables) { string columnList = ""; for (int i = 0; i < table.Columns.Count; i++) { if (i == 0) columnList = table.Columns[0].ColumnName; else columnList += "," + table.Columns[i].ColumnName; } var da = new SqlDataAdapter("SELECT " + columnList + " FROM " + table.TableName, conn); var builder = new SqlCommandBuilder(da); builder.ConflictOption = ConflictOption.OverwriteChanges; da.RowUpdating += onUpdatingRow; da.Update(ds, table.TableName); } } catch (....) { ..... } } Here's the event handler for the RowUpdating event: public static void onUpdatingRow(object sender, SqlRowUpdatingEventArgs e) { if ((e.StatementType == StatementType.Update) && (e.Command == null)) { e.Command = CreateUpdateCommand(e.Row, sender as SqlDataAdapter); e.Status = UpdateStatus.Continue; } } and the CreateUpdateCommand method: private static SqlCommand CreateUpdateCommand(DataRow row, SqlDataAdapter da) { string whereClause = ""; string setClause = ""; SqlConnection conn = da.SelectCommand.Connection; for (int i = 0; i < row.Table.Columns.Count; i++) { char quoted; if ((row.Table.Columns[i].DataType == Type.GetType("System.String")) || (row.Table.Columns[i].DataType == Type.GetType("System.DateTime"))) quoted = '\''; else quoted = ' '; string val = row[i].ToString(); if (row.Table.Columns[i].DataType == Type.GetType("System.Boolean")) val = (bool)row[i] ? "1" : "0"; bool isPrimaryKey = false; for (int j = 0; j < row.Table.PrimaryKey.Length; j++) { if (row.Table.PrimaryKey[j].ColumnName == row.Table.Columns[i].ColumnName) { if (whereClause != "") whereClause += " AND "; if (row[i] == DBNull.Value) whereClause += row.Table.Columns[i].ColumnName + "=NULL"; else whereClause += row.Table.Columns[i].ColumnName + "=" + quoted + val + quoted; isPrimaryKey = true; break; } } /* Only values for column that is not a primary key can be modified */ if (!isPrimaryKey) { if (setClause != "") setClause += ", "; if (row[i] == DBNull.Value) setClause += row.Table.Columns[i].ColumnName + "=NULL"; else setClause += row.Table.Columns[i].ColumnName + "=" + quoted + val + quoted; } } return new SqlCommand("UPDATE " + row.Table.TableName + " SET " + setClause + " WHERE " + whereClause, conn); } However, this is really slow when we have a lot of records. Is there a way to optimize this or an entirely different way to send lots of udpate/delete on several tables? I would really much like to use TSQL for this but can't figure a way to send a dataset to a regular sproc. Additional notes: We cannot directly access the SQLServer database. We tried without compression and it was slower.

    Read the article

  • Patterns for implementing field change tracking.

    - by David
    Hi all For one of my recent projects, I had to implement field change tracking. So anytime the user changed a value of a field, the change was recorded in order to allow full auditing of changes. In the database, I implemented this as a single table 'FieldChanges' with the following fields: TableName, FieldName, RecordId, DateOfChange, ChangedBy, IntValue, TextValue, DateTimeValue, BoolValue. The sproc saving changes to an object determines for each field whether it has been changed and inserts a record into FieldChanges if it has: if the type of the changed field is int, it records it in the IntValue field in the FieldChanges table, etc. This means that for any field in any table with any id value, I can query the FieldChanges table to get a list of changes. This works quite well but is a bit clumsy. Can anyone else who has implemented similar functionality suggest a better approach, and why they think it's better? I'd be really interested - thanks. David

    Read the article

  • Is it possible to "merge" the values of multiple records into a single field without using a stored

    - by j0rd4n
    A co-worker posed this question to me, and I told them, "No, you'll need to write a sproc for that". But I thought I'd give them a chance and put this out to the community. Essentially, they have a table with keys mapping to multiple values. For a report, they want to aggregate on the key and "mash" all of the values into a single field. Here's a visual: --- ------- Key Value --- ------- 1 A 1 B 1 C 2 X 2 Y The result would be as follows: --- ------- Key Value --- ------- 1 A,B,C 2 X,Y They need this in SQLServer 2005. Again, I think they need to write a stored procedure, but if anyone knows a magic out-of-the-box function that does this, I'd be impressed.

    Read the article

  • Changing a SUM returned NULL to zero

    - by Lee_McIntosh
    I have a Stored Procedure as follows: CREATE PROC [dbo].[Incidents] (@SiteName varchar(200)) AS SELECT ( SELECT SUM(i.Logged) FROM tbl_Sites s INNER JOIN tbl_Incidents i ON s.Location = i.Location WHERE s.Sites = @SiteName AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0) GROUP BY s.Sites ) AS LoggedIncidents 'tbl_Sites contains a list of reported on sites. 'tbl_Incidents containts a generated list of total incidents by site/date (monthly) 'If a site doesnt have any incidents that month it wont be listed. The problem I'm having is that a site doesnt have any Incidents this month and as such i get a NULL value returned for that site when i run this sproc, but i need to have a zero/0 returned to be used within a chart in SSRS. I've tried the using coalesce and isnull to no avail. SELECT COALESCE(SUM(c.Logged,0)) SELECT SUM(ISNULL(c.Logged,0)) Is there a way to get this formatted correctly? Cheers, Lee

    Read the article

  • what the true nature of @ in Transct-SQL

    - by Richard77
    Hello, I reading some old ScottGu's blogs on Linq2SQL. Now I'm doing the SPROC part. I'd like to know what's the exact meaning of @variable. See this from ScottGu's Blog ALTER PROCEDURE dbo.GetCustomersDetails ( @customerID nchar(5), @companyName nvarchar(40) output ) AS SELECT @companyName = CompanyName FROM Customers WHERE CustomerID = @customerID SELECT * FROM Orders WHERE CustomerID = @customerID ORDER BY OrderID I'm kind of lost as, so far, I've though of anything preceded by a '@' as a placeholder for user input. But, in the example above, it looks like '@companyName' is used as a regular variable like in C# for instance (SELECT @companyName = ...). But, @companyName is not known yet. So, what the true nature a something preceded by a '@' like above? a vriable? a simple placeholder to accommodate user entered value? Thanks for helping

    Read the article

  • Fastest way to calculate summary of database field

    - by Jo-wen
    I have a ms-sql table with the following structure: Name nvarchar; Sign nvarchar; Value int example contents: Test1, 'plus', 5 Test1, 'minus', 3 Test2, 'minus', 1 I would like to have totals per "Name". (add when sign = plus, subtract when sign = minus) result: Test1, 2 Test2, -1 I want to show these results (and update them when a new record is added)... and I'm looking for the fastest solution! [sproc? fast-forward cursor? calculate in .net?]

    Read the article

  • Small methods - Small sprocs

    - by Berlioz
    Uncle Bob recommends having small methods. Do stored procedures have an ideal size? Or can they run on for 100's and 100's of lines long? Also does anyone have anything to say about where to place business logic. If located in stored procedures, the database is being used as data processing tier. If you read Adam Machanic, his bias is toward the database, does that imply long stored procedures that only the author of the sproc understands, leaving maintainers to deal with the mess? I guess there is two inter-related questions, somehow. Thanks in advance for responding to a fuzzy question(s).

    Read the article

  • Stored Procedure for Multi-Table Insert Error: Cannot Insert the Value Null into Column

    - by SidC
    Good Evening All, I've created the following stored procedure: CREATE PROCEDURE AddQuote -- Add the parameters for the stored procedure here AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; Declare @CompanyName nvarchar(50), @Addr nvarchar(50), @City nvarchar(50), @State nvarchar(2), @Zip nvarchar(5), @NeedDate datetime, @PartNumber float, @Qty int -- Insert statements for procedure here Insert into dbo.Customers (CompanyName, Address, City, State, ZipCode) Values (@CompanyName, @Addr, @City, @State, @Zip) Insert into dbo.Orders (NeedbyDate) Values(@NeedDate) Insert into dbo.OrderDetail (fkPartNumber,Qty) Values (@PartNumber,@Qty) END GO When I execute AddQuote, I receive an error stating: Msg 515, Level 16, State 2, Procedure AddQuote, Line 31 Cannot insert the value NULL into column 'ID', table 'Diel_inventory.dbo.OrderDetail'; column does not allow nulls. INSERT fails. The statement has been terminated. I understand that I've set Qty field to not allow nulls and want to continue doing so. However, are there other syntax changes I should make to ensure that this sproc works correctly? Thanks, Sid

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >