I Think I Found A BUG With Either Newid() Or Derived Tables

Apr 3, 2008

Hello.So the scenario is a little complicated.I am joining two tables.Table 1 is derived; it has one row; it has a column based from newid()Table 2 joins to table 1 and reuses the newid() value from table 1 in table 2's rowsBecause there is only one row in Table 1, the value of newid() REPEATS in Table 2The bug is that the NewId() value from Table1 is REGENERATED with every Table 2 record.I created a blog about this because it takes a code sample to demonstrate:http://jerrytech.blogspot.com/2008/04/sql-2005-tsql-bug-with-newid-in-derived.html

Have a nice day;
Jerry

View 2 Replies


ADVERTISEMENT

Derived Tables

Feb 2, 2004

OK....I know how to write a query to return for example :

All the people that ordered X and Y

but how do I write one for:

All the people that ordered X but not Y?


Thanks,
Trey

View 1 Replies View Related

Derived Tables

Dec 12, 2006

Hi. We have to create an export from our system to be imported into another system. To get the data out we need to create some SQl but we're struggling a bit.

I presently have the following code

SELECT ProSolution.dbo.StudentDetail.RefNo, ProSolution.dbo.StudentDetail.FirstForename, ProSolution.dbo.StudentDetail.Surname,

ProSolution.dbo.StudentDetail.MobileTel, ProSolution.dbo.StudentDetail.RestrictedUseIndicatorID, ProSolution.dbo.Enrolment.CompletionStatusID,

ProSolution.dbo.Offering.Code

FROM ProSolution.dbo.StudentDetail INNER JOIN

ProSolution.dbo.Enrolment ON ProSolution.dbo.StudentDetail.StudentDetailID = ProSolution.dbo.Enrolment.StudentDetailID INNER JOIN

ProSolution.dbo.Offering ON ProSolution.dbo.Enrolment.OfferingID = ProSolution.dbo.Offering.OfferingID

WHERE (ProSolution.dbo.StudentDetail.AcademicYearID = '06/07') AND (ProSolution.dbo.StudentDetail.RestrictedUseIndicatorID = '9') AND

(ProSolution.dbo.Enrolment.CompletionStatusID = '1')




The above code returns the data one line per course but we need it to be one line per student with all their courses on one line too, like follows.

567897 Tom Smith 07111 111111 TCFT1 CKSAN1 DHICS

Can anyone give us any guidance please?

Thanks
Chip

View 16 Replies View Related

Scope In Derived Tables

Jun 29, 2007

This is kind of what I'm trying to do in my MS SQL 2000 query. ShouldI be able to reference s1.col1 inside the 2nd derived table?I'm getting 'Invalid column name col1' and it's coming from the 2ndderived table (I've commented out other refs to just it to check).Maybe I need to use a temp table instead.SELECT s1.col1,(SELECT * FROM(SELECT COUNT(zzz) AS SomeTotalFROM tab1WHERE s1.col1 = zzz)) AS RowCount) /* error here */FROM(SELECT col1 FROM table) AS s1Thank you!

View 1 Replies View Related

Derived Tables Are UPDATABLE Or NOT ????

Sep 28, 2007

Hi,
In the SQL92 Specifications i read the foloowingf statement...
"All base tables are updatable. Derived tables are either updatable or read-only. The operations of insert, update, and delete are
permitted for updatable tables, subject to constraining Access
Rules. The operations of insert, update, and delete are not allowed
for read-only tables."
But i am concentrating on the below line from the above written lines,
"Derived tables are either updatable or read-only."
I want to ask that is derived tables are updatable or not??? if yes then how,???i tried the following querry but its not working...





Code Block

Update (select * from test1) AS de SET id=0
????

View 10 Replies View Related

Derived Tables From Multiple Resultsets

Oct 19, 2005

Hi!I want to return a derived table along with 4 simple tables in a storedprocedure as follows:Input parameter: @FtNum (==Order Number, selects one Order and allassociated data)Table 1: OrdersTable 2: ItemsTable 3: InstancesTable 4: StockDetailsDerived Table: for each Item that requires stock items, 1st columnshould receive the ItemNo (from Items), subsequent columns should receive thedetails from StockDetails via the common key field 'StockCode'.I have so far used a 'Fetch' cursor to find all occurrences of a StockCodewithin the Items table, but have been unable to figure out how to first addthe ItemNo into the temporary table.Code is as follows:... build #tmp_StockDECLARE stock_cursor CURSOR FORSELECT StockCode, ItemNoFROM ItemsWHERE FtNum = @FtNumORDER BY ItemNoOPEN stock_cursorFETCH NEXT FROM stock_cursorINTO @StockCode, @ItemNoWHILE @@FETCH_STATUS = 0BEGININSERT INTO #tmp_Stock-- wish to insert ItemNo = @ItemNo here --SELECT *FROM ControlledStockWHERE StockCode = @StockCodeFETCH NEXT FROM stock_cursorINTO @Stockcode, @ItemNoENDOf course there may be a much simpler way to do this!Your help would be greatly appreciated either way.--Message posted via SQLMonster.comhttp://www.sqlmonster.com/Uwe/Forum...eneral/200510/1

View 2 Replies View Related

Temp, Variable, Derived Tables

Feb 26, 2008

Two point to discuss

1) Temp table, variable table and derived tables,

they all seem same to me. Is there any big difference among them.

Also, if I do have the tables avaiable, so now I don't think I have to create any of the temerory tables,
since I can use the

WITh mystatement ( )
Select * from mystatmment

I think if I have to use any of the temperory tables , only time when I have to just create some tables to test some values on in it rather then using the real table in the database.

2) And not only that I use the CTE for that but for any sub query whereever apply, i would like to forget about the IN, Exit or = in the correlated queries but would use whereever I can use the "Joins"

I would like other point of view on that.
Thanks

View 1 Replies View Related

Create Multiple INNER JOIN On Derived Tables

Mar 10, 2014

create multiple INNER JOIN on derived tables as I have written below or use a #temp table for all derived tables and use them into JOIN. This below query is also very hard to understand what is going on .

CREATE TABLE #Temp
(
NumPlayers INT,
ModuleID INT,
ClientId INT,
ASF_Version VARCHAR(10),
ASF_VersionHead INT

[code]....

View 1 Replies View Related

Searching A List Of Tables, Derived From Another Table

Sep 21, 2005

Relative SQL newbie here......this is probably easy, but....Lets say I have a table (MainTable) that stores a list of input table names,a primary key (PKey), and a field called "Configured" for each one. Each ofthese input tables also contain a field called "Configured", which is set totrue or false in another process based on an OrderNumber. (So an order'sinputs are stored in several input tables, and the MainTable is a summarytable that shows which input tables have been configured for any givenOrderNumber).What I need to do is open each input table, and look for a record containinga specific OrderNumber and where Configured=true. If a record is found, Ineed to update the Configured field for that table in the MainTable, andthen move on to the next sub-table.The way I'm doing it now is with simple SQL and loops. Here is the basiccode (ASP):*****************************************OrderNumber = "562613" ' the current order that is being processed' reset all configured flagssql = "UPDATE MainTable SET Configured = 0"conn.execute sql, , &H00000080' get list of all tablenamessql = "SELECT InputTableName, PKey FROM MainTable WHERE InputTableName <>'---'"set rsTableNames = conn.execute(sql)while not rsTableNames.eof' test each input table for configured flagsql = "SELECT Configured FROM " & rsTableNames("InputTableName")& _" WHERE Configured = 1 AND OrderNumber = '" & OrderNumber &"'"set rs = conn.execute(sql)If Not rs.EOF Then' update the main tablesql = "UPDATE MainTable SET Configured = 1 WHERE PKey='" &rsTableNames("PrimaryKey") & "'"conn.execute sql, , &H00000080end ifset rs = nothingrsTableNames.movenextwend*****************************************There has to be a faster way.. I think.... maybe something that could bewritten as a stored procedure? I use a similar technique in a couple ofother places and it's a bit of a performance hit, especially as the numberof input tables grows.TIA!Calan

View 6 Replies View Related

Paging Records On SQL Server Using Derived Tables

Jan 24, 2007

I am using derived tables to Page data on the SQL Server side.I used this link as my mentor for doing paging on the SQLServerhttp://msdn2.microsoft.com/en-us/library/ms979197.aspxI wanted to use USER PAGING, thus I used the following code:CREATE PROCEDURE UserPaging(@currentPage int = 1, @pageSize int =1000)ASDECLARE @Out int, @rowsToRetrieve int, @SQLSTRING nvarchar(1000)SET @rowsToRetrieve = (@pageSize * @currentPage)SET NOCOUNT ONSET @SQLSTRING = N'selectCustomerID,CompanyName,ContactName,ContactTitle from( SELECT TOP '+ CAST(@pageSize as varchar(10)) +'CustomerId,CompanyName,ContactName,ContactTitle from( SELECT TOP ' + CAST(@rowsToRetrieve as varchar(10)) +'CustomerID,CompanyName,ContactName,ContactTitle FROM( SELECT TOP ' + CAST(@rowsToRetrieve as varchar(10)) +'CustomerID,CompanyName,ContactName,ContactTitle FROM Customers as T1ORDER BY contactname) AS T2 ORDER BY contactname DESC ) AS T3)As T4 ORDER BY contactname ASC'EXEC(@SQLSTRING)RETURNGOWhen I use this. Assume that the Total records returned by the SQLquery is 1198.Thus when I am on Page1 the above Stored Proc (SP) willreturn the first 1000 records.This works absolutely fine.Now I am on Page2, now I need to retrieve only the remaining 198records.But if I use the above SP, it will return the last 1000records.So to tweak this I used the following logic to set the@pagesize variable:Declare @PageCount intselect @PageCount = @TotalRows/@PageSizeif @currentPage @PageCount SET @PageSize = @TotalRows%@PageSizeSince I am on Page2 the above logic will set the PageSize to 198 andnot 1000.But when I use this logic, it takes forever for the SP toreturn the 198 records in a resultset.However if the TotalRows were = 1800, and thus the PageSize=800 orgreater, this SP returns the resultset quickly enough.Thus to get over this problem I had to use the other logic i.e. usingApplication Paging (i.e. first storing the entire result set into aTemp table, then retrieving only the required records for the PAGE)Can anyone suggest what is wrong with my user paging logic?????TIA...

View 1 Replies View Related

Paging Records On SQL Server Using Derived Tables : More Question

Jan 25, 2007

I did use query plans to find out more. ( Please see the thread BELOW)I have a question on this, if someone can help me with that it will begreat.In my SQL query that selects data from table, I have a where clausewhich states :where PermitID like @WorkTypeorder by WorkStart DESC@WorkType is a input parameter to the Stored proc and its value is'01%'When I use the above where clause, all the Sorts in the ESTIMATED QueryExecution plan show me a COST of 28%.However if I change the query manually to say:where PermitID like '01%'order by WorkStart DESCThe COST of the Sort (in ESTIMATED Query Execution plan) reduces to 2%and at the beginning of the PLAN, there is a Bookmark Lookup whichincludes the above where clause.Whereas with the FIRST example , the BookMark Lookup in the beginningdoesn't show that where condition.Can anyone help me better understand this anomaly?TIA=====================================I am using derived tables to Page data on the SQL Server side.I used this link as my mentor for doing paging on the SQLServerhttp://msdn2.microsoft.com/en-us/library/ms979197.aspxI wanted to use USER PAGING, thus I used the following code:CREATE PROCEDURE UserPaging(@currentPage int = 1, @pageSize int =1000)ASDECLARE @Out int, @rowsToRetrieve int, @SQLSTRING nvarchar(1000)SET @rowsToRetrieve = (@pageSize * @currentPage)SET NOCOUNT ONSET @SQLSTRING = N'selectCustomerID,CompanyName,ContactName,ContactTitle from( SELECT TOP '+ CAST(@pageSize as varchar(10)) +'CustomerId,CompanyName,ContactName,ContactTitle from( SELECT TOP ' + CAST(@rowsToRetrieve as varchar(10)) +'CustomerID,CompanyName,ContactName,ContactTitle FROM( SELECT TOP ' + CAST(@rowsToRetrieve as varchar(10)) +'CustomerID,CompanyName,ContactName,ContactTitle FROM Customers as T1ORDER BY contactname) AS T2 ORDER BY contactname DESC ) AS T3)As T4 ORDER BY contactname ASC'EXEC(@SQLSTRING)RETURNGOWhen I use this. Assume that the Total records returned by the SQLquery is 1198.Thus when I am on Page1 the above Stored Proc (SP) willreturn the first 1000 records.This works absolutely fine.Now I am on Page2, now I need to retrieve only the remaining 198records.But if I use the above SP, it will return the last 1000records.So to tweak this I used the following logic to set the@pagesize variable:Declare @PageCount intselect @PageCount = @TotalRows/@PageSizeif @currentPage @PageCount SET @PageSize = @TotalRows%@PageSizeSince I am on Page2 the above logic will set the PageSize to 198 andnot 1000.But when I use this logic, it takes forever for the SP toreturn the 198 records in a resultset.However if the TotalRows were = 1800, and thus the PageSize=800 orgreater, this SP returns the resultset quickly enough.Thus to get over this problem I had to use the other logic i.e. usingApplication Paging (i.e. first storing the entire result set into aTemp table, then retrieving only the required records for the PAGE)Can anyone suggest what is wrong with my user paging logic?????TIA...

View 8 Replies View Related

ORDER BY Clause Is Invalid In Views / Inline Functions / Derived Tables / Subqueries

Sep 25, 2013

The data I am pulling is correct I just cant figure out how to order by the last 8 numbers that is my NUMBER column. I tried adding FOR XML AUTO to my last line in my query: From AP_DETAIL_REG where AP_BATCH_ID = 1212 and NUMBER is not null order by NUMBER FOR XML AUTO) as Temp(DATA) where DATA is not null

but no change same error.
Output:
1234567890000043321092513 00050020

Select DATA from(
select '12345678'+
left( '0', 10-len(cast ( CONVERT(int,( INV_AMT *100)) as varchar))) +
cast (CONVERT(int,(INV_AMT*100)) as varchar) +
left('0',2-len(CAST (MONTH(DATE) as varchar(2))))+
CAST (MONTH(DATE) as varchar(2)) +
left('0',2-len(CAST (day(CHECK_DATE) as varchar(2)))) +
CAST (day(DATE) as varchar(2))+right(cast
(year(DATE)

[code]....

View 6 Replies View Related

Tables Joined On Multiple Columns, Exclude Records Found In Table A

Nov 7, 2006

I'm using SQL server 200

Table A has columns CompressedProduct, Tool, Operation

Table B in a differnt database has columns ID, Product, Tool Operation

I cannot edit table A. I can select records from A and insert into B. And I can select only the records that are in both tables.

But I want to be able to select any records that are in table A but not in Table B.

ie. I want to select records from A where the combination of Product, Tool and Operaton does not appear in Table B, even if all 3 on their own do appear.

This code return all the records from A. I need to filter out the records found in Table B.

---------------------------------------------------------------------------------------------------------------------------------

SELECT ID, CompressedProduct, oq.Tool, oq.Operation FROM OPENQUERY (Lisa_Link,
'SELECT DISTINCT CompressedProduct, Tool, Operation FROM tblToolStatus ts
JOIN tblProduct p ON ts.ProductID = p.ProductID
JOIN tblTool t ON ts.ToolID = t.ToolID
JOIN tblOperation o ON ts.OperationID = o.OperationID
WHERE ts.ToolID=66
') oq
LEFT JOIN Family f on oq.CompressedProduct = f.Product and oq.Tool = f.Tool and oq.Operation = f.Operation

View 1 Replies View Related

Regarding Newid

Apr 9, 2007

Dear Folks,
can you please tell me, how many newid's can be generated by an sql server instance? and the newid generated by one instance can possibly be generated by another instance ? please give me brief regarding this


thank you very much

Vinod

View 1 Replies View Related

NEWID()

Nov 23, 2005

Is there a limitation of using:set @sessionID = NEWID()would there be a simular NEWID() being generated if used in a databaseapplication.Eugene Anthony*** Sent via Developersdex http://www.developersdex.com ***

View 1 Replies View Related

NewID

Mar 1, 2007

Hello,

I use VB.Net and SQL CE 2.0. I'd like to start using UniqueIdentifier fields as my primary keys.

I saw that this would return a NewID value


System.Guid.NewGuid().ToString()

however, it is not supported in Compact Framework. So how can one obtain the next NewId()?

Thank you.

View 1 Replies View Related

Newid() Question

Jul 10, 2006

when you use newid() is that a new uniqueidentifier for the database or for the table???I have a changelog that captures newly created users first and gives them a newid, then i want to approve that change and copy the newid generated for that user into the user table.  Will I run into duplicate id's that way???

View 1 Replies View Related

Need More SQL Query NewID Help

Jul 7, 2006

Excuse my ignorance because I don't do advance db related programming,but have no other choice at the moment. My experience is limited tosimple queries.I need to have the following query display the recordset in random orderbased on RecordID (unique key) if possible. I tried the ORDER BY NewID()at the end and it generated an error (ORDER BY items must appear in theselect list if SELECT DISTINCT is specified.) I guess because of the subquery. I would also like for the recordset to display a different 10records on each hit to the page, not just the same 10 records in randomorder. I wasn't sure if the SELECT commands I have in place aresufficient for this task.Thanks in advance for any assistance.SELECT DISTINCTTOP 10 dbo.ShowcaseRides.RecordID,dbo.ShowcaseRides.CustomerID, dbo.ShowcaseRides.PhotoLibID,dbo.ShowcaseRides.Year,dbo.ShowcaseRides.MakeShowcase,dbo.ShowcaseRides.ModelShowcase, dbo.ShowcaseRides.VehicleTitle,dbo.ShowcaseRides.NickName,dbo.ShowcaseRides.SiteURL,dbo.ShowcaseRides.ShowcaseRating, dbo.ShowcaseRides.ShowcaseRatingImage,dbo.ShowcaseRides.ReviewDate,dbo.ShowcaseRides.Home,dbo.ShowcaseRides.EntryDate, dbo.Customers.UserName,dbo.Customers.ShipCity, dbo.Customers.ShipRegion,dbo.Customers.ShipPostalCode,dbo.Customers.ShipCountry, dbo.Customers.LastName,dbo.Customers.FirstName, dbo.Customers.MemberSince,dbo.ShowcaseRides.Live,dbo.ShowcaseRides.MemberLive, dbo.Accessories.Make,dbo.Accessories.Model, Photos.PathFROM dbo.ShowcaseRides INNER JOINdbo.Customers ON dbo.ShowcaseRides.CustomerID =dbo.Customers.CustomerID INNER JOINdbo.Accessories ON dbo.ShowcaseRides.MakeShowcase= dbo.Accessories.MakeShowcase ANDdbo.ShowcaseRides.ModelShowcase =dbo.Accessories.ModelShowcase INNER JOIN(SELECT MIN(dbo.ShowcasePhotos.PhotoPath)AS Path, RecordIDFROM dbo.ShowcasePhotosGROUP BY RecordID) Photos ONdbo.ShowcaseRides.RecordID = Photos.RecordID INNER JOINdbo.ShowcasePhotos ON Photos.Path =dbo.ShowcasePhotos.PhotoPathWHERE (dbo.ShowcaseRides.MemberLive = 1) AND (dbo.ShowcaseRides.Live= 1) AND (dbo.ShowcaseRides.MakeShowcase = @MMColParam)ORDER BY dbo.ShowcaseRides.EntryDate DESCRegards,Darin L. MillerParadyse Development~-~-~-~-~-~-~-~-~-~-~-~-~-~-"Some things are true whether you believe them or not." - Nicolas Cagein City of Angels

View 3 Replies View Related

Integration Services :: How To Declare Multiple Derived Column In SSIS Derived Column Task

Jul 22, 2015

how to declare multiple derived columns in SSIS Derived Column Task in one attempt.as i have around 150 columns coming from Flat file. I had created the required Expression in Excel and now i want add those in derived column task but its allowing only 1 expression at a time.

View 4 Replies View Related

Cross Apply And Newid

Apr 28, 2008

Hi,

Why am I getting a different numbers of distinct ids in those queries?


USE AdventureWorks
go
Declare @myXml as xml
set @myXml = '
<lol>omg</lol>
<lol>rofl</lol>
';

select locations.*, T.c.value('.','nvarchar(max)') from
(
select newid() as Id
from Production.ProductModel
where ProductModelID in (7, 8)
) as locations cross apply @myXml.nodes('(/lol)') T(c);

select mytable.* , T.c.value('.','nvarchar(max)') from
(
select newid() as Id
union
select newid()
) as mytable cross apply @myXml.nodes('(/lol)') T(c);


Thanks,

Victor

View 8 Replies View Related

Prob With Rowguid Using Newid() Fn

Apr 23, 2006

hi guys

cant find the prob, please help

ALTER TABLE [dbo].[tblUserDetails]
ALTER COLUMN [UserDetailRowGUID] [uniqueidentifier] set default newid()
go

error:Incorrect syntax near the keyword 'default'.

cm

View 2 Replies View Related

Cross Apply And Newid

Apr 28, 2008

I've been trying to figure out why these two return a different amount of distinct ids...
Is that a bug in optimization?




Code Snippet


USE AdventureWorks
go
Declare @myXml as xml
set @myXml = '
<lol>omg</lol>
<lol>rofl</lol>
';

WITH locations as
(
select newid() as Id
from Production.ProductModel
where ProductModelID in (7, 8)
)
select locations.*, T.c.value('.','nvarchar(max)') from locations cross apply @myXml.nodes('(/lol)') T(c);

with mytable as
(
select newid() as Id
union
select newid()
)
select mytable.* , T.c.value('.','nvarchar(max)') from mytable cross apply @myXml.nodes('(/lol)') T(c);

View 4 Replies View Related

VIEWS With Columns Set By NEWID()

Sep 30, 2006

I have a view which at the moment has no unique identifier on each record. When I try adding a column definition to the view such as NEWID() as TransactionId, the view then cannot 1) be selected into a temporary table, or 2) queried on other columns in the table. In either case I end up with an empty result set.

I believe I have a way around this for my purpose, which was principally testability. However, can anyone enlighten me as to how and why this happens?

Andrew Raymond

View 5 Replies View Related

NewID(), UniqueIdentifier Is It Unique Across Different SQL Servers?

Apr 23, 2001

I have an application being developed using SQL server.
The data is captured at various remote areas and the
SQL servers are not physically connected to each other.

Periodically either through a replication / backup process
i plan to update the data from various servers into a central
database.

Can i use the NewID() function to generate a unique ID which
i can use as a primary key that would not be duplicated
across all these servers?

if not Please suggest a solution to maintain the uniqueness
of the transaction.

thanks in advance

View 1 Replies View Related

Distinct Random Rows Using NewID()

May 26, 2008

I have 2 tables, Artists and Artworks.
I have a query:

SELECT TOP (4) dbo.Artists.ArtistID, dbo.Artists.FirstName + ' ' + dbo.Artists.LastName AS FullName, dbo.Artworks.ArtworkName, dbo.Artworks.Image
FROM dbo.Artists INNER JOIN
dbo.Artworks ON dbo.Artists.ArtistID = dbo.Artworks.ArtistID
ORDER BY NEWID()

This query returns random images, but the artists are sometimes repeated.
I would like to have DISTINCT Random Artists returned, each with a random image. I tried various subqueries, but I just get error messages.
Any help would be appreciated.
Thnks,

Paolo

View 8 Replies View Related

Using NEWID() As A Parameter To A Stored Procedure

Jul 20, 2005

Is it possible to use NEWID() as a parameter to a stored procedure inSQL Server 2000. I keep getting a "Line 1: Incorrect syntax near ')'"error.ALTER PROCEDURE dbo.StoredProcedure1(@x uniqueidentifier)AS/* SET NOCOUNT ON */RETURNStoredProcedure1 NEWID()go"Line 1: Incorrect syntax near ')'"Thanks in advance

View 1 Replies View Related

Retrieve Guid After Inserting Recrod With NEWID()

Mar 3, 2007

Hi There,
I'm having a problem retreiving the auto generated Guid after inserting anew record with NEWID(), my stored proc is as follows:SET @uiTransactionID = NEWID()
INSERT INTO Transactions (uiTransactionID) VALUES (@uiTransactionID)
IF @@ERROR = 0 AND @@ROWCOUNT = 1
BEGIN
SELECT @uiTransactionID AS '@@GUID'
RETURN 0
END
 And the return on my insert statement is:
command.ExecuteNonQuery();m_uiTransactionID = (Guid)command.Parameters["RETURN_VALUE"].Value;
I can never retreive the newly generated Guid, can onyone spot where i'm going wrong?
Many thanks
Ben

View 2 Replies View Related

SqlParameter With ParameterName '@NewID' Is Not Contained By This SqlParameterCollection

Mar 27, 2007

Hi,What I am trying to do is to get the new ID for every record is inserted into a table. I have a For...Each statement that does the loop and using the sqldatasource to so the insert.   <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ myConnectionString%>">
<InsertParameters>
<asp:Parameter Name="NewID" Type="int16" Direction="output" />
</InsertParameters>
</asp:SqlDataSource>  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sqlSelect As String
Session("Waste_Profile_Num") = 2
Session("Waste_Profile_Num2") = 5

sqlSelect = "SELECT Range, Concentration, Component_ID FROM Component_Profile WHERE (Waste_Profile_Num = " & Session("Waste_Profile_Num").ToString() & ")"
SqlDataSource1.SelectCommand = sqlSelect

Dim dv As Data.DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), Data.DataView)
For Each dr As Data.DataRow In dv.Table.Rows

sqlSelect = "INSERT INTO Component_Profile (Waste_Profile_Num, Range, Concentration, Component_ID) "
sqlSelect &= "VALUES (" & Session("Waste_Profile_Num2").ToString() & ", @Range, @Concentration, @Component_ID); SELECT @NewID = @@Identity"
SqlDataSource1.InsertCommand = sqlSelect
'SqlDataSource1.InsertParameters.Add("Waste_Profile_Num", Session("Waste_Profile_Num2").ToString())
SqlDataSource1.InsertParameters.Add("Range", dr("Range").ToString())
SqlDataSource1.InsertParameters.Add("Concentration", dr("Concentration").ToString())
SqlDataSource1.InsertParameters.Add("Component_ID", dr("Component_ID").ToString())
SqlDataSource1.Insert()
SqlDataSource1.InsertParameters.Clear()
MsgBox(Session("NewID").ToString())

Next

End Sub

Protected Sub SqlDataSource1_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Inserted
Session("NewID") = e.Command.Parameters("@NewID").Value.ToString

End Sub  What I have done so far is to display the new id and I am going to use that return id later. However, the first time through the loop, I am able to get the new id but not the second time. So, I wonder, how do I every single new id each time the INSERT statement is executed?STAN   

View 5 Replies View Related

Do I Need To Verify That NewID() Returns A Unique GUID?

Oct 26, 2007

 I'm migrating a web based system to SQL server.  I'm planning on using the SQL server function NewID() to create unique keys for many of my records in many different tables.  I'm just wondering if NewID() is guaranteed to return a value that does not already exist in my database.  I mean obviously once you have a certain number of records (a hell of a lot) you'd be breaking the odds to never come up with a duplicate. Do I need to make sure the result of NEWID() doesn't already exist?Thanks 

View 1 Replies View Related

Problem Updating Existing Records With Newid()

Apr 23, 2008

I currently have a table called stores.  I've just added a uniqueidentifier column called store_guid to the stores table.  The table currently has about 500 records in it and now i'm trying to set each store_guid = to a newid().  I've tried using  UPDATE stores SET store_guid = newid()  .   however, that doesn't work because i think it's trying to set each record equal to the same guid using that approach.  All i need to do is fill in my new column with new guids.  any ideas?
 
Thanks in advance,
 

View 3 Replies View Related

Dynamic SQL And NewID Function - Pulling Random Records

Jun 11, 2007

I'm trying to use the NEWID function in dynamic SQL and get an errormessage Incorrect syntax near the keyword 'ORDER'. Looks like I can'tdo an insert with an Order by clause.Here's the code:SELECT @SQLString = N'INSERT INTO TMP_UR_Randoms(Admit_DOCID,Client_ID, SelectDate, SelectType,RecordChosen)'SELECT @SQLString = @SQLString + N'(SELECT TOP ' + @RequFilesST + 'Admit_DOCID, Client_ID, SelectDate, SelectType, RecordChosen FROMFD__UR_Randoms 'SELECT @SQLString = @SQLString + N'WHERE SelectType = ' +@CodeRevTypeSt + ' AND SelectDate = ''' + @TodaySt + '''' + ' ORDERBY NEWID())'execute sp_executesql @SQLStringMy goal is to get a random percentage of records.The full SP follows. In a nutshell - I pull a set of records fromFD__Restart_Prog_Admit into a temporary table called FD__UR_Randoms.I need to retain the set of all records that COULD be eligible forselection. Based on the count of those records, I calculate how manyneed to be pulled - and then need to mark those records as "chosen".I'd just as soon not use the TMP_UR_Randoms table - I went that routebecause I ran into trouble with a #Tmp table in the above SQL.Can anyone help with this? Thanks in advance.Full SQL:CREATE PROCEDURE TP_rURRandomReview @ReviewType varchar(30)--Review type will fill using Crystal Parameter (setting defaults)AS/* 6.06.2007UR Requirements:(1) Initial 4-6 month review: 15% of eligible admissions(eligible via days in program and not yet discharged) must be reviewed4-6 months after admission. This review will be done monthly -meaning we'll have a moving target of names (with overlaps) whichcould be pulled from each month. (Minimum 5 records)(2) Subsequent 6-12 month review: Out of those already reviewed(in #1), we must review 25% of them (minimum of 5 records)(3) Initial 6-12 month review: Exclude any included in 1 or 2 -review 25% of admissions in program from 6-12 months (minimum 5)*/DECLARE @CodeRevType intDECLARE @PriorRec int -- number of records already markedeligible (in case user hits button more than once on same day for sametype of review)DECLARE @CurrRec int --number of eligible admitsDECLARE @RequFiles intDECLARE @SQLString nvarchar(1000)DECLARE @RequFilesSt varchar(100)DECLARE @CodeRevTypeSt char(1)DECLARE @TodayNotime datetimeDECLARE @TodaySt varchar(10)--strip the time off todaySELECT @TodayNotime = DateAdd(day,datediff(day,0,GetDate()),0)--convert the review type to a codeSelect @CodeRevType = Case @ReviewType when 'Initial 4 - 6 Month' then1 when 'Initial 6 - 12 Month' then 2 when 'Subsequent 6 - 12 month'then 3 END--FD__UR_Randoms always gets filled when this is run (unless it waspreviously run)--Check to see if the review was already pulled for this recordSELECT @PriorRec = (Select Count(*) FROM FD__UR_Randoms whereSelectType = @CodeRevType and SelectDate = @TodayNotime)If @PriorRec 0 GOTO ENDThis--************************************STEP A: Populate FD__UR_Randomstable with records that are candidates for review************************If @CodeRevType = 1BEGININSERT INTO FD__UR_Randoms (Admit_DOCID, Client_ID, SelectDate,SelectType,RecordChosen)(SELECT pa.OP__DOCID, pa.Client_ID,Convert(varchar(10),GetDate(),101) as SelectDate, @CodeRevType, 'F'FROM dbo.FD__RESTART_PROG_ADMIT paInner join FD__Client cOn pa.Client_ID = c.Client_IDWHERE Left(c.Fullname,2) <'TT' AND (Date_Discharge IS NULL)AND(DATEDIFF(d, Date_Admission, GETDATE()) 119)AND (DATEDIFF(d, Date_Admission, GETDATE()) <= 211)AND pa.OP__DOCID not in (Select Admit_DOCID from FD__UR_Randomswhere RecordChosen = 'T'))ENDIf @CodeRevType = 2--only want those that were selected in a batch 1 - in program 6-12months; selected for first reviewBEGININSERT INTO FD__UR_Randoms (Admit_DOCID, Client_ID, SelectDate,SelectType,RecordChosen)(SELECT pa.OP__DOCID, pa.Client_ID,Convert(varchar(10),GetDate(),101) as SelectDate, @CodeRevType, 'F'FROM dbo.FD__RESTART_PROG_ADMIT paInner join FD__Client cOn pa.Client_ID = c.Client_IDWHERE Left(c.Fullname,2) <'TT' AND (Date_Discharge IS NULL)AND(DATEDIFF(d, Date_Admission, GETDATE()) 211)AND (DATEDIFF(d, Date_Admission, GETDATE()) < 364)AND pa.OP__DOCID in (Select Admit_DOCID from FD__UR_Randomswhere SelectType = 1 AND RecordChosen= 'T'))ENDIf @CodeRevType = 3--only want those that were not in batch 1 or 2 - in program 6 to 12monthsBEGININSERT INTO FD__UR_Randoms (Admit_DOCID, Client_ID, SelectDate,SelectType,RecordChosen)(SELECT pa.OP__DOCID, pa.Client_ID,Convert(varchar(10),GetDate(),101) as SelectDate, @CodeRevType, 'F'FROM dbo.FD__RESTART_PROG_ADMIT paInner join FD__Client cOn pa.Client_ID = c.Client_IDWHERE Left(c.Fullname,2) <'TT' AND (Date_Discharge IS NULL)AND(DATEDIFF(d, Date_Admission, GETDATE()) 211)AND (DATEDIFF(d, Date_Admission, GETDATE()) < 364)AND pa.OP__DOCID NOT in (Select Admit_DOCID from FD__UR_Randomswhere SelectType < 3 AND RecordChosen= 'T'))ENDSELECT @CurrRec = (Select Count(*) FROM FD__UR_Randoms whereSelectType = @CodeRevType and SelectDate = @TodayNoTime)--*************************************STEP B Pick the necessarypercentage **************************************--if code type = 1, 15% otherwise 25%If @CodeRevType = 1BEGINSELECT @RequFiles = (@CurrRec * .15)ENDELSEBEGINSELECT @RequFiles = (@CurrRec * .25)END--make sure we have at least 5If @RequFiles < 5BEGINSELECT @RequFiles = 5End--*************************************STEP C Randomly select thatmany files**************************************--convert all variables to stringsSELECT @RequFilesSt = Convert(Varchar(100),@RequFiles)SELECT @CodeRevTypeSt = Convert(Char(1),@CodeRevType)SELECT @TodaySt = Convert(VarChar(10),@TodayNoTime,101)SELECT @SQLString = N'INSERT INTO TMP_UR_Randoms(Admit_DOCID,Client_ID, SelectDate, SelectType,RecordChosen)'SELECT @SQLString = @SQLString + N'(SELECT TOP ' + @RequFilesST + 'Admit_DOCID, Client_ID, SelectDate, SelectType, RecordChosen FROMFD__UR_Randoms 'SELECT @SQLString = @SQLString + N'WHERE SelectType = ' +@CodeRevTypeSt + ' AND SelectDate = ''' + @TodaySt + '''' + ' ORDERBY NEWID())'print @SQLStringexecute sp_executesql @SQLStringSELECT * FROM TMP_UR_Randoms/*--This select statement gives me what i want but I need to somehowmark these records and/or move this subset into the temp tableSelect Top @RequFilesFROM FD__UR_RandomsWHERE SelectType = @CodeRevType and SelectDate =Convert(varchar(10),GetDate(),101))ORDER BY NewID()*/ENDTHIS:GO

View 3 Replies View Related

How To Retrieve The GUID Value Of A SQL NewID() Identity Column After An Insert ?

Jan 10, 2006

Hello,

In my table, i've a GUID column type. I insert a new record with NewID() function in Sql request.

Is it possible to retreive the GUID column of this new record (without requerying the table) ?

I'm using EVC, Sql Mobile 3.0 and OLE DB interface.

Thanks in advance.

View 1 Replies View Related

The Connection Is Not Found. This Error Is Thrown By Connections Collection When The Specific Connection Element Is Not Found

May 1, 2007

I've got a package which reads a text file into a table and updates another. I set up configurations so that I could import it into the SSIS store on both my dev and live servers. Now, I'm getting this error. I tried removing the configs and am still getting it.

I've been through each step and everything looks okay. Does anyone have any idea (a) what's wrong, (b) how to localise the error or (c) get any additional information? Or do I just have to recreate the package from scratch?



TITLE: Package Validation Error
------------------------------

Package Validation Error

------------------------------
ADDITIONAL INFORMATION:

Error at PartnerLinkFlatFileImporter: The connection "" is not found. This error is thrown by Connections collection when the specific connection element is not found.

Error at PartnerLinkFlatFileImporter [Log provider "SSIS log provider for SQL Server"]: The connection manager "" is not found. A component failed to find the connection manager in the Connections collection.

(Microsoft.DataTransformationServices.VsIntegration)

------------------------------
BUTTONS:

OK
------------------------------

View 20 Replies View Related







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