Search Results

Search found 95 results on 4 pages for 'newid'.

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

  • Joining on NULLs

    - by Dave Ballantyne
    A problem I see on a fairly regular basis is that of dealing with NULL values.  Specifically here, where we are joining two tables on two columns, one of which is ‘optional’ ie is nullable.  So something like this: i.e. Lookup where all the columns are equal, even when NULL.   NULL’s are a tricky thing to initially wrap your mind around.  Statements like “NULL is not equal to NULL and neither is it not not equal to NULL, it’s NULL” can cause a serious brain freeze and leave you a gibbering wreck and needing your mummy. Before we plod on, time to setup some data to demo against. Create table #SourceTable ( Id integer not null, SubId integer null, AnotherCol char(255) not null ) go create unique clustered index idxSourceTable on #SourceTable(id,subID) go with cteNums as ( select top(1000) number from master..spt_values where type ='P' ) insert into #SourceTable select Num1.number,nullif(Num2.number,0),'SomeJunk' from cteNums num1 cross join cteNums num2 go Create table #LookupTable ( Id integer not null, SubID integer null ) go insert into #LookupTable Select top(100) id,subid from #SourceTable where subid is not null order by newid() go insert into #LookupTable Select top(3) id,subid from #SourceTable where subid is null order by newid() If that has run correctly, you will have 1 million rows in #SourceTable and 103 rows in #LookupTable.  We now want to join one to the other. First attempt – Lets just join select * from #SourceTable join #LookupTable on #LookupTable.id = #SourceTable.id and #LookupTable.SubID = #SourceTable.SubID OK, that’s a fail.  We had 100 rows back,  we didn’t correctly account for the 3 rows that have null values.  Remember NULL <> NULL and the join clause specifies SUBID=SUBID, which for those rows is not true. Second attempt – Lets deal with those pesky NULLS select * from #SourceTable join #LookupTable on #LookupTable.id = #SourceTable.id and isnull(#LookupTable.SubID,0) = isnull(#SourceTable.SubID,0) OK, that’s the right result, well done and 99.9% of the time that is where its left. It is a relatively trivial CPU overhead to wrap ISNULL around both columns and compare that result, so no problems.  But, although that’s true, this a relational database we are using here, not a procedural language.  SQL is a declarative language, we are making a request to the engine to get the results we want.  How we ask for them can make a ton of difference. Lets look at the plan for our second attempt, specifically the clustered index seek on the #SourceTable   There are 2 predicates. The ‘seek predicate’ and ‘predicate’.  The ‘seek predicate’ describes how SQLServer has been able to use an Index.  Here, it has been able to navigate the index to resolve where ID=ID.  So far so good, but what about the ‘predicate’ (aka residual probe) ? This is a row-by-row operation.  For each row found in the index matching the Seek Predicate, the leaf level nodes have been scanned and tested using this logical condition.  In this example [Expr1007] is the result of the IsNull operation on #LookupTable and that is tested for equality with the IsNull operation on #SourceTable.  This residual probe is quite a high overhead, if we can express our statement slightly differently to take full advantage of the index and make the test part of the ‘Seek Predicate’. Third attempt – X is null and Y is null So, lets state the query in a slightly manner: select * from #SourceTable join #LookupTable on #LookupTable.id = #SourceTable.id and ( #LookupTable.SubID = #SourceTable.SubID or (#LookupTable.SubID is null and #SourceTable.SubId is null) ) So its slightly wordier and may not be as clear in its intent to the human reader, that is what comments are for, but the key point is that it is now clearer to the query optimizer what our intention is. Let look at the plan for that query, again specifically the index seek operation on #SourceTable No ‘predicate’, just a ‘Seek Predicate’ against the index to resolve both ID and SubID.  A subtle difference that can be easily overlooked.  But has it made a difference to the performance ? Well, yes , a perhaps surprisingly high one. Clever query optimizer well done. If you are using a scalar function on a column, you a pretty much guaranteeing that a residual probe will be used.  By re-wording the query you may well be able to avoid this and use the index completely to resolve lookups. In-terms of performance and scalability your system will be in a much better position if you can.

    Read the article

  • Using ROWLOCK in an INSERT statement (MS SQL)

    - by RPS
    Would it be wise to use ROWLOCK on an insert statement that is copying large amounts of data and inserting it into the same table? Ex) INSERT INTO TABLE with (rowlock) (id, name) select newid, name) from TABLE with (nolock) where id = 1 Does anybody have recommendations on how to improve this statement, as I see when MS SQL gets busy it will end in Timeout Query returned for MS SQL.

    Read the article

  • SQL Server 2008: FileStream Insertion Failure w/ .NET 3.5SP1

    - by James Alexander
    I've configured a db w/ a FileStream group and have a table w/ File type on it. When attempting to insert a streamed file and after I create the table row, my query to read the filepath out and the buffer returns a null file path. I can't seem to figure out why though. Here is the table creation script: /****** Object: Table [dbo].[JobInstanceFile] Script Date: 03/22/2010 18:05:36 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[JobInstanceFile]( [JobInstanceFileId] [int] IDENTITY(1,1) NOT NULL, [JobInstanceId] [int] NOT NULL, [File] [varbinary](max) FILESTREAM NULL, [FileId] [uniqueidentifier] ROWGUIDCOL NOT NULL, [Created] [datetime] NOT NULL, CONSTRAINT [PK_JobInstanceFile] PRIMARY KEY CLUSTERED ( [JobInstanceFileId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] FILESTREAM_ON [JobInstanceFilesGroup], UNIQUE NONCLUSTERED ( [FileId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] FILESTREAM_ON [JobInstanceFilesGroup] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[JobInstanceFile] ADD DEFAULT (newid()) FOR [FileId] GO Here's my proc I call to create the row before streaming the file: /****** Object: StoredProcedure [dbo].[JobInstanceFileCreate] Script Date: 03/22/2010 18:06:23 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO create proc [dbo].[JobInstanceFileCreate] @JobInstanceId int, @Created datetime as insert into JobInstanceFile (JobInstanceId, FileId, Created) values (@JobInstanceId, newid(), @Created) select scope_identity() GO And lastly, here's the code I'm using: public int CreateJobInstanceFile(int jobInstanceId, string filePath) { using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConsumerMarketingStoreFiles"].ConnectionString)) using (var fileStream = new FileStream(filePath, FileMode.Open)) { connection.Open(); var tran = connection.BeginTransaction(IsolationLevel.ReadCommitted); try { //create the JobInstanceFile instance var command = new SqlCommand("JobInstanceFileCreate", connection) { Transaction = tran }; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@JobInstanceId", jobInstanceId); command.Parameters.AddWithValue("@Created", DateTime.Now); int jobInstanceFileId = Convert.ToInt32(command.ExecuteScalar()); //read out the filestream transaction context to stream the file for storage command.CommandText = "select [File].PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() from JobInstanceFile where JobInstanceFileId = @JobInstanceFileId"; command.CommandType = CommandType.Text; command.Parameters.AddWithValue("@JobInstanceFileId", jobInstanceFileId); using (SqlDataReader dr = command.ExecuteReader()) { dr.Read(); //get the file path we're writing out to string writePath = dr.GetString(0); using (var writeStream = new SqlFileStream(writePath, (byte[])dr.GetValue(1), FileAccess.ReadWrite)) { //copy from one stream to another byte[] bytes = new byte[65536]; int numBytes; while ((numBytes = fileStream.Read(bytes, 0, 65536)) 0) writeStream.Write(bytes, 0, numBytes); } } tran.Commit(); return jobInstanceFileId; } catch (Exception e) { tran.Rollback(); throw e; } } } Can someone please let me know what I'm doing wrong. In the code, the following expression is returning null for the file path and shouldn't be: //get the file path we're writing out to string writePath = dr.GetString(0); The server is different then the computer the code is running on but the necessary shares appear to be in order and I have also run the following: EXEC sp_configure filestream_access_level, 2 Any help would be greatly appreciated. Thanks!

    Read the article

  • wxPython ListCtrl Column Ignores Specific Fields

    - by g.d.d.c
    I'm rewriting this post to clarify some things and provide a full class definition for the Virtual List I'm having trouble with. The class is defined like so: from wx import ListCtrl, LC_REPORT, LC_VIRTUAL, LC_HRULES, LC_VRULES, \ EVT_LIST_COL_CLICK, EVT_LIST_CACHE_HINT, EVT_LIST_COL_RIGHT_CLICK, \ ImageList, IMAGE_LIST_SMALL, Menu, MenuItem, NewId, ITEM_CHECK, Frame, \ EVT_MENU class VirtualList(ListCtrl): def __init__(self, parent, datasource = None, style = LC_REPORT | LC_VIRTUAL | LC_HRULES | LC_VRULES): ListCtrl.__init__(self, parent, style = style) self.columns = [] self.il = ImageList(16, 16) self.Bind(EVT_LIST_CACHE_HINT, self.CheckCache) self.Bind(EVT_LIST_COL_CLICK, self.OnSort) if datasource is not None: self.datasource = datasource self.Bind(EVT_LIST_COL_RIGHT_CLICK, self.ShowAvailableColumns) self.datasource.list = self self.Populate() def SetDatasource(self, datasource): self.datasource = datasource def CheckCache(self, event): self.datasource.UpdateCache(event.GetCacheFrom(), event.GetCacheTo()) def OnGetItemText(self, item, col): return self.datasource.GetItem(item, self.columns[col]) def OnGetItemImage(self, item): return self.datasource.GetImg(item) def OnSort(self, event): self.datasource.SortByColumn(self.columns[event.Column]) self.Refresh() def UpdateCount(self): self.SetItemCount(self.datasource.GetCount()) def Populate(self): self.UpdateCount() self.datasource.MakeImgList(self.il) self.SetImageList(self.il, IMAGE_LIST_SMALL) self.ShowColumns() def ShowColumns(self): for col, (text, visible) in enumerate(self.datasource.GetColumnHeaders()): if visible: self.columns.append(text) self.InsertColumn(col, text, width = -2) def Filter(self, filter): self.datasource.Filter(filter) self.UpdateCount() self.Refresh() def ShowAvailableColumns(self, evt): colMenu = Menu() self.id2item = {} for idx, (text, visible) in enumerate(self.datasource.columns): id = NewId() self.id2item[id] = (idx, visible, text) item = MenuItem(colMenu, id, text, kind = ITEM_CHECK) colMenu.AppendItem(item) EVT_MENU(colMenu, id, self.ColumnToggle) item.Check(visible) Frame(self, -1).PopupMenu(colMenu) colMenu.Destroy() def ColumnToggle(self, evt): toggled = self.id2item[evt.GetId()] if toggled[1]: idx = self.columns.index(toggled[2]) self.datasource.columns[toggled[0]] = (self.datasource.columns[toggled[0]][0], False) self.DeleteColumn(idx) self.columns.pop(idx) else: self.datasource.columns[toggled[0]] = (self.datasource.columns[toggled[0]][0], True) idx = self.datasource.GetColumnHeaders().index((toggled[2], True)) self.columns.insert(idx, toggled[2]) self.InsertColumn(idx, toggled[2], width = -2) self.datasource.SaveColumns() I've added functions that allow for Column Toggling which facilitate my description of the issue I'm encountering. On the 3rd instance of this class in my application the Column at Index 1 will not display String values. Integer values are displayed properly. If I add print statements to my OnGetItemText method the values show up in my console properly. This behavior is not present in the first two instances of this class, and my class does not contain any type checking code with respect to value display. It was suggested by someone on the wxPython users' group that I create a standalone sample that demonstrates this issue if I can. I'm working on that, but have not yet had time to create a sample that does not rely on database access. Any suggestions or advice would be most appreciated. I'm tearing my hair out on this one.

    Read the article

  • How to format and add new numbers dynamically to hidden field?

    - by Bartek
    I get from server into client side only pure number IDs, how to add dynamically it to html hidden field so that looks like array or JSON format (I mean: ["32","33","34"]), so that in next step I can receive on serwer and parse? Hidden field contains on start only blank brackets []. My current code override hidden field from [] to e.g. "32": $("#myHiddenField").val(JSON.stringify(data.result[0].newid));

    Read the article

  • UUID collision risk using different algorithms

    - by Diego Jancic
    Hi Guys, I have a database where 2 (or maybe 3 or 4) different applications are inserting information. The new information has IDs of the type GUID/UUID, but each application is using a different algorithm to generate the IDs. For example, one is using the NHibernate's "guid.comb", other is using the SQLServer's NEWID(), other might want to use .NET's Guid.NewGuid() implementation. Is there an above normal risk of ID collision or duplicates? Thanks!

    Read the article

  • Using ROWLOCK in an INSERT statement (SQL Server)

    - by RPS
    Would it be wise to use ROWLOCK on an insert statement that is copying large amounts of data and inserting it into the same table? Ex) INSERT INTO TABLE with (rowlock) (id, name) SELECT newid, name FROM TABLE with (nolock) WHERE id = 1 Does anybody have recommendations on how to improve this statement, as I see when SQL Server gets busy it will end in Timeout Query returned for SQL Server.

    Read the article

  • What does ON [PRIMARY] mean?

    - by Icono123
    I'm creating an SQL setup script and I'm using someone else's script as an example. Here's an example of the script: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[be_Categories]( [CategoryID] [uniqueidentifier] ROWGUIDCOL NOT NULL CONSTRAINT [DF_be_Categories_CategoryID] DEFAULT (newid()), [CategoryName] [nvarchar](50) NULL, [Description] [nvarchar](200) NULL, [ParentID] [uniqueidentifier] NULL, CONSTRAINT [PK_be_Categories] PRIMARY KEY CLUSTERED ( [CategoryID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO Does anyone know what the ON [PRIMARY] command does? Regards.

    Read the article

  • Marking multi-level nested forms as "dirty" in Rails

    - by Charles Kihe
    I have a three-level multi-nested form in Rails. The setup is like this: Projects have many Milestones, and Milestones have many Notes. The goal is to have everything editable within the page with JavaScript, where we can add multiple new Milestones to a Project within the page, and add new Notes to new and existing Milestones. Everything works as expected, except that when I add new notes to an existing Milestone (new Milestones work fine when adding notes to them), the new notes won't save unless I edit any of the fields that actually belong to the Milestone to mark the form "dirty"/edited. Is there a way to flag the Milestone so that the new Notes that have been added will save? Edit: sorry, it's hard to paste in all of the code because there's so many parts, but here goes: Models class Project < ActiveRecord::Base has_many :notes, :dependent => :destroy has_many :milestones, :dependent => :destroy accepts_nested_attributes_for :milestones, :allow_destroy => true accepts_nested_attributes_for :notes, :allow_destroy => true, :reject_if => proc { |attributes| attributes['content'].blank? } end class Milestone < ActiveRecord::Base belongs_to :project has_many :notes, :dependent => :destroy accepts_nested_attributes_for :notes, :allow_destroy => true, :allow_destroy => true, :reject_if => proc { |attributes| attributes['content'].blank? } end class Note < ActiveRecord::Base belongs_to :milestone belongs_to :project scope :newest, lambda { |*args| order('created_at DESC').limit(*args.first || 3) } end I'm using an jQuery-based, unobtrusive version of Ryan Bates' combo helper/JS code to get this done. Application Helper def add_fields_for_association(f, association, partial) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render(partial, :f => builder) end end I render the form for the association in a hidden div, and then use the following JavaScript to find it and add it as needed. JavaScript function addFields(link, association, content, func) { var newID = new Date().getTime(); var regexp = new RegExp("new_" + association, "g"); var form = content.replace(regexp, newID); var link = $(link).parent().next().before(form).prev(); if (func) { func.call(); } return link; } I'm guessing the only other relevant piece of code that I can think of would be the create method in the NotesController: def create respond_with(@note = @owner.notes.create(params[:note])) do |format| format.js { render :json => @owner.notes.newest(3).all.to_json } format.html { redirect_to((@milestone ? [@project, @milestone, @note] : [@project, @note]), :notice => 'Note was successfully created.') } end end The @owner ivar is created in the following before filter: def load_milestone @milestone = @project.milestones.find(params[:milestone_id]) if params[:milestone_id] end def determine_owner @owner = load_milestone @owner ||= @project end Thing is, all this seems to work fine, except when I'm adding new notes to existing milestones. The milestone has to be "touched" in order for new notes to save, or else Rails won't pay attention.

    Read the article

  • Create MSDB Folders Through Code

    You can create package folders through SSMS, but you may also wish to do this as part of a deployment process or installation. In this case you will want programmatic method for managing folders, so how can this be done? The short answer is, go and look at the table msdb.dbo. sysdtspackagefolders90. This where folder information is stored, using a simple parent and child hierarchy format. To add new folder directly we just insert into the table - INSERT INTO dbo.sysdtspackagefolders90 ( folderid ,parentfolderid ,foldername) VALUES ( NEWID() -- New GUID for our new folder ,<<Parent Folder GUID>> -- Lookup the parent folder GUID if a child or another folder, or use the root GUID 00000000-0000-0000-0000-000000000000 ,<<Folder Name>>) -- New folder name There are also some stored procedures - sp_dts_addfolder sp_dts_deletefolder sp_dts_getfolder sp_dts_listfolders sp_dts_renamefolder To add a new folder to the root we could call the sp_dts_addfolder to stored procedure - EXEC msdb.dbo.sp_dts_addfolder @parentfolderid = '00000000-0000-0000-0000-000000000000' -- Root GUID ,@name = 'New Folder Name The stored procedures wrap very simple SQL statements, but provide a level of security, as they check the role membership of the user, and do not require permissions to perform direct table modifications.

    Read the article

  • Entity Framework - SaveChanges with GUID as EntityKey

    - by MissingLinq
    I have a SQL Server 2008 database table that uses uniqueidentifier as a primary key. On inserts, the key is generated on the database side using the newid() function. This works fine with ADO.NET. But when I set up this table as an entity in an Entity Framework 4 model, there's a problem. I am able to query the entity just fine, but when creating a new entity and invoking SaveChanges() on the context, the generated uniqueidentifier on the database is all zeros. I understand there was an issue with EF v1 where this scenario did not work, requiring creating the GUID on the client prior to calling SaveChanges. However, I had read in many places that they were planning to fix this in EF 4. My question -- is this scenario (DB-side generation of uniqueidentifier) still not supported in EF4? Are we still stuck with generating the GUID on the client?

    Read the article

  • What does transaction.commit() do when the flushmode is set manual in Hibernate?

    - by wei
    Here is a block of code in the Java Persistence with Hibernate book by Christian and Gavin, Session session = getSessionFactory().openSession(); session.setFlushMode(FlushMode.MANUAL); // First step in the conversation session.beginTransaction(); Item item = (Item) session.get(Item.class, new Long(123) ); session.getTransaction().commit(); // Second step in the conversation session.beginTransaction(); Item newItem = new Item(); Long newId = (Long) session.save(newItem); // Triggers INSERT! session.getTransaction().commit(); // Roll back the conversation! session.close();//enter code here I am confused that why the first step and second step need to be wrapped into two separate transactions? Since the flushmode is set manual here, no operations (suppose we ignore the insert here) will hit the database anyway. So why bother with transactions here? thanks

    Read the article

  • Mysql and Subsonic 3 with LINQ: Cannot insert rows

    - by Gustavo
    I'm using Susbsonic 3 with the LINQ templates. I've already added a column called 'ID' to my Articles table. When I try to insert a row using the following code var db = new LDB(); int newID = db.Insert.Into<ArticlesTable> ( x => x.Description ).Values( "TestDescription" ).Execute(); I get the following error message Can't decide which property to consider the Key - you can create one called 'ID' or mark one with SubSonicPrimaryKey attribute Any clue on what I'm doing wrong?

    Read the article

  • Change Large Number of Record Keys using Map Table

    - by Coyote
    I have a set of records indexed by id numbers, I need to convert these record's indexes to a new id number. I have a two column table mapping the old numbers to the new numbers. For example given these two tables, what would the update statement look like? Given: OLD_TO_NEW oldid | newid ----------------- 1234 0987 7698 5645 ... ... and id | data ---------------- 1234 'yo' 7698 'hey' ... ... Need: id | data ---------------- 0987 'yo' 5645 'hey' ... ... This oracle so I have access to PL/SQL, I'm just trying to avoid it.

    Read the article

  • SQL Server 2008 GUID column is all 0's

    - by Andy Evans
    I'm hoping this is a simple goof I did on my end ... I have a table in my database set up like so: column name: widget_guid data type: uniqueidentifier allow nulls: false default value: newid() identity: false row guid: true When records are created (via LINQ to SQL) that the values in this field are formatted as a GUID but contain all 0's My assumption was that when a new record was created, that a guid would be autogenerated for that column, much like an auto-incrementing row id. Is this not true? Any help would be greatly appreciated. Thanks.

    Read the article

  • Auto-generated values for columns in database

    - by Jamal
    Is it a good practice to initialize columns that we can know their values in database, for example identity columns of type unique identifier can have a default value (NEWID()), or columns that shows the record create date can have a default value (GETDATE()). Should I go through all my tables and do this whereever I am sure that I won't need to assign the value manually and the Auto-generated value is correct. I am also thinking about using linq-to-sql classes and setting the "Auto Generated Value" property of these columns to true. Maybe this is what everybody already knows or maybe I am asking a question about a fundamental issue, if so please tell me.

    Read the article

  • MSSQL - Select one random record not showing duplicates

    - by Lukes123
    I have two tables, events and photos, which relate together via the 'Event_ID' column. I wish to select ONE random photo from each event and display them. How can I do this? I have the following which displays all the photos which are associated. How can I limit it to one per event? SELECT Photos.Photo_Id, Photos.Photo_Path, Photos.Event_Id, Events.Event_Title, Events.Event_StartDate, Events.Event_EndDate FROM Photos, Events WHERE Photos.Event_Id = Events.Event_Id AND Events.Event_EndDate < GETDATE() AND Events.Event_EndDate IS NOT NULL AND Events.Event_StartDate IS NOT NULL ORDER BY NEWID() Thanks Luke Stratton

    Read the article

  • SQL 2008 GUID column is all 0's

    - by Andy Evans
    I'm hoping this is a simple goof I did on my end ... I have a table in my database set up like so: column name: widget_guid data type: uniqueidentifier allow nulls: false default value: newid() identity: false row guid: true When records are created (via LINQ to SQL) that the values in this field are formatted as a GUID but contain all 0's My assumption was that when a new record was created, that a guid would be autogenerated for that column, much like an auto-incrementing row id. Is this not true? Any help would be greatly appreciated. Thanks.

    Read the article

  • SQL Server - Select one random record not showing duplicates

    - by Lukes123
    I have two tables, events and photos, which relate together via the 'Event_ID' column. I wish to select ONE random photo from each event and display them. How can I do this? I have the following which displays all the photos which are associated. How can I limit it to one per event? SELECT Photos.Photo_Id, Photos.Photo_Path, Photos.Event_Id, Events.Event_Title, Events.Event_StartDate, Events.Event_EndDate FROM Photos, Events WHERE Photos.Event_Id = Events.Event_Id AND Events.Event_EndDate < GETDATE() AND Events.Event_EndDate IS NOT NULL AND Events.Event_StartDate IS NOT NULL ORDER BY NEWID() Thanks Luke Stratton

    Read the article

  • Random select is not always returning a single row.

    - by Lieven
    The intention of following (simplified) code fragment is to return one random row. Unfortunatly, when we run this fragment in the query analyzer, it returns between zero and three results. As our input table consists of exactly 5 rows with unique ID's and as we perform a select on this table where ID equals a random number, we are stumped that there would ever be more than one row returned. Note: among other things, we already tried casting the checksum result to an integer with no avail. DECLARE @Table TABLE ( ID INTEGER IDENTITY (1, 1) , FK1 INTEGER ) INSERT INTO @Table SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 SELECT * FROM @Table WHERE ID = ABS(CHECKSUM(NEWID())) % 5 + 1

    Read the article

  • Query to get row from one table, else random row from another

    - by Jimmy
    tblUserProfile - I have a table which holds all the Profile Info (too many fields) tblMonthlyProfiles - Another table which has just the ProfileID in it (the idea is that this table holds 2 profileids which sometimes become monthly profiles (on selection)) Now when I need to show monthly profiles, I simply do a select from this tblMonthlyProfiles and Join with tblUserProfile to get all valid info. If there are no rows in tblMonthlyProfile, then monthly profile section is not displayed. Now the requirement is to ALWAYS show Monthly Profiles. If there are no rows in monthlyProfiles, it should pick up 2 random profiles from tblUserProfile. If there is only one row in monthlyProfiles, it should pick up only one random row from tblUserProfile. What is the best way to do all this in one single query ? I thought something like this select top 2 * from tblUserProfile P LEFT OUTER JOIN tblMonthlyProfiles M on M.profileid = P.profileid ORder by NEWID() But this always gives me 2 random rows from tblProfile. How can I solve this ?

    Read the article

  • MySQL customized join query using multiple tables

    - by itgeek
    I am searching one student from each class from one group. There are different class groups and every group has different classes and every class has multiple students. See below: Group1 --> Class1, Class2 etc Class1 --> GreenStudent1, GreenStudent2 etc Class2 --> RedStudent1, RedStudent2 etc ------------------------------------------------------ SELECT table1.id, table1.myname, table1.marks table2.studentid, table2.studentname FROM table1 INNER JOIN table3 ON table1.oldid = table3.id INNER JOIN table2 ON table2.studentid = table3.newid WHERE table1.classgroup = 'SCI79' GROUP BY table1.oldid ORDER BY table1.marks DESC There are different joins applied in the query. Above mentioned query giving me correct results but I need little modification in it. Current query returning me one student from each class. What I need? I need one student from each class but only that student who has MAXIMUM table1.marks So I should have one student from each class who has maximum number in their relevant classes. Can anyone suggest some solution or rewrite this query? Thanks :)

    Read the article

  • Programmatic binding of accelerators in wxPython

    - by Inductiveload
    I am trying to programmatically create and bind a table of accelerators in wxPython in a loop so that I don't need to worry about getting and assigning new IDs to each accelerators (and with a view to inhaling the handler list from some external resource, rather than hard-coding them). I also pass in some arguments to the handler via a lambda since a lot of my handlers will be the same but with different parameters (move, zoom, etc). The class is subclassed from wx.Frame and setup_accelerators() is called during initialisation. def setup_accelerators(self): bindings = [ (wx.ACCEL_CTRL, wx.WXK_UP, self.on_move, 'up'), (wx.ACCEL_CTRL, wx.WXK_DOWN, self.on_move, 'down'), (wx.ACCEL_CTRL, wx.WXK_LEFT, self.on_move, 'left'), (wx.ACCEL_CTRL, wx.WXK_RIGHT, self.on_move, 'right'), ] accelEntries = [] for binding in bindings: eventId = wx.NewId() accelEntries.append( (binding[0], binding[1], eventId) ) self.Bind(wx.EVT_MENU, lambda event: binding[2](event, binding[3]), id=eventId) accelTable = wx.AcceleratorTable(accelEntries) self.SetAcceleratorTable(accelTable) def on_move(self, e, direction): print direction However, this appears to bind all the accelerators to the last entry, so that Ctrl+Up prints "right", as do all the other three. How to correctly bind multiple handlers in this way?

    Read the article

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