.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

How to use the table which is created with CTE(Common Table Expression) more than one select,insert

Posted By:      Posted Date: September 26, 2010    Points: 0   Category :Sql Server

I faced one problem while working with Common Table expressions in Sqlserver 2008.

the problem is How to use the table(means temporary table)  which is created  by with  CTE's after that one select statement.

Actaully the table(which is created using with CTE) is automatically deleted, one's after execution of any select,insert,update or create view statement .Right!

But I needed that table second time also. How it is possible.

please help if any one knows..........

Thanks in Advance........


View Complete Post

More Related Resource Links

Reviewer suggested common table expression instead of adding 12 fields

So during a code review a DB Mgr suggested that I use a common table function instead of adding the fields below. No idea how to possibly do this. Anyone have any ideas? Here is a code snippet that he wants to lose: SELECT   LP .leaseID, sum   (paymentAmount1+paymentAmount2+paymentAmount3+paymentAmount4+paymentAmount5+paymentAmount6+paymentAmount7+paymentAmount8+paymentAmount9+paymentAmount10+paymentAmount11+paymentAmount12) as restPayment FROM   leasePaymentScheduleDetails AS L inner join leasePaymentSchedules AS LP ON L.leasePaymentScheduleID = LP.leasePaymentScheduleID WHERE   paymentYear>=@curyear+5 GROUP   BY LP .leaseID   Any input is appreciated.

Common Table expression

Common Table Expression(CTE) is aexpression which will be
called recursively until the condition is satisfied. It's
introduced in Sql Server 2005. This can be used in both
Select and DML statements. The result set generated by the
CTE is same as a hybrid Derived Table meets declared Temporary

Conditional insert: If select return rows, insert rows to table otherwise insert specific row indica

This is what I have

Insert into ReportDetail( Partcipantid, Reportid)  

select distinct ParticipantID , 9 from OpenCredit

      except select ParticipantID, 9 from StoreCredit where Closed = 0

 Issue is that when above select statement returns no row, it seems like no record is

Best way to insert newly-created UserId into a second table also



I have set up the ASP.NET Membership system using MS SQL. I have also created a new table (Table2) in which the user can store additional information. The UserId column is present in both tables (Table2's UserId column is the foreign key to the UserId column in aspnet_Membership). When a new user creates their account, what is the best way to also automatically insert that user's unique UserId into a new Table2 record at the same time (obviously in the column UserId)?

Below is my attempt to do this. Not sure this is right, but I used the oncreateduser property of CreateUserWizard and called the method below -- not sure if it would work (but regardless, I'm getting the error message at bottom of this post). Please help.

Thank you.


Sub CreateUserWizard1_CreatedUser(ByVal sender As Object, ByVal e As System.EventArgs)

            Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDatabaseConnectionString").ToString())
                ' Create a command object.
                Dim cmd As New SqlCom

Common Expression table vs Derived table


Hello ,

I have read about Common expression table . and I have read the following :

   " Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query"  .

  I want to know what does it mean ? and I need a sample to understand it .




Insert value using Table Value Functions

a real gem in Sql Server 2008. mostly people still using Stored procedure may be they shifted to SQL Server but they are not using TVF right now.

Data Points: Common Table Expressions


In T-SQL, views and derived tables serve similar purposes and have their advantages. But when working with SQL Server 2005,there's a third option--using Common Table Expressions (CTEs). John Papa explains.

John Papa

MSDN Magazine October 2007

Regular Expression to Match


Here is the kind of text I want to match via a regular Expression

The id="dgSchedule" is always present in the TAG but its location may differ

The table is span over multiple line/contains white spaces/tabs...

I have the regular expression to match the start and end tag respectively over a single line

\<table .*\>


The problem is to match the whole table span over multiple lines

<table cellspacing="0" rules="all" border="1" id="dgSchedule" style="border-style:None;height:100%;width:100%;border-collapse:collapse;">
	<tr class="blackbar" align="center" style="background-color:#7FB4DE;font-family:Verdana;font-weight:bold;height:20px;">
		<td>From Place</td><td>To Place</td><td>Time</td><td>Bus Type</td>

	</tr><tr style="background-color:#DEECF5;">
	</tr><tr style="background-color:#EFF5FA;">
	</tr><tr style="background-color:#DEECF5;">


Need to add value to table on insert



I'm fairly new to .NET.  I need to add values CreatedBy, CreatedDate, ModifiedBy, ModifiedDate to the record before inserting it to the database. 

Please see code below. 

     [MetadataType (typeof(GRIPSMetaData))]
    public partial class SchoolDistrict
        internal void OnSaving(ChangeAction changeAction)
            if (changeAction == ChangeAction.Insert)
              this.CreatedBy = 5;
              this.CreatedDate = DateTime.Now;
            else if (changeAction == ChangeAction.Update)
                this.CreatedBy = 5;

How to setup db diagram to automatically insert username into table?

 I have a table setup in the database for users who are basically going to create a classified listing.  How can I setup a diagram that would easily create a table relationship with the Users table, so that it automatically inserts the users username when they submit a new ad?  If so, how?  I've tried adding a UserName row to my table and creating a relationship with the Users table "UserName" row, but it wasn't accepting the relationship when I tried to save the diagram...apparently because the UserName row in the Users table isn't a primary key?Also, one this is setup, what's the best way to provide the user a way to see a list of their ads and have the ability to edit them?

SELECT statement to return NULL by matching data from another table.

Hi,I am fairly new at SQL and I have been struggling for days now trying to find an answer to my problem and i have come to the point where i have run out of ideas and about to give up. I'm hoping someone can put me in the correct path. The problem I have 3 table Table 1 Department" has the following columns: REF, NAME Table 2  "Department_Collection" has the following columns: REF, DEPARTMENT_REF, MANAGER_REF, STORE_REF, ACTIVE Table 3 Store" has the following columns: REF, NAME, STORE_ID  What i am trying to do is to take all the rows in the Department table and get a matching row (DEPARTMENT.NAME, DEPARTMENT_COLLECTION.REF) from the Department_Collection table, if it does not match any then still display DEPARTMENT.NAME but mark DEPARTMENT_COLLECTION.REF as null. I have tried the following select statement but it seem to remove all null values when supplied with a 'storename' SELECT DEPARTMENT.NAME, DEPARTMENT_COLLECTION.REF FROM DEPARTMENT_COLLECTION right outer join DEPARTMENT on DEPARTMENT_COLLECTION.DEPARTMENT_REF = DEPARTMENT.REF left outer join STORE on DEPARTMENT_COLLECTION.STORE_REF = STORE.REF where STORE.NAME = 'storename' order by DEPARTMENT.NAME   Any help will be greatly appreciated. Thanks

select max record to join another table sybase

select a.pono,(select (user) from user where userid=a.userid having date=max(date)) as user from a inner join b on a.no=b.no  in the result , i have selected the same id and retrieve two records every thing are same except the date how can i select the record out of two record which date is max date as the where Clasuse to select correct user poid    date                name 1        12/08/2010      Mary 1        20/08/2010      Peter   now i would like to select name which id=1 and date is max and then use the name to join another table because name is foreign key  

reading xml data and insert into database table

hi friends, .very urgent for me so only i send following script i create for read xml data and to import to table. i got result for reading xml and rows are added to table but the values are showing null pls clarify this problem. thanks alter procedure pizza_sales ( @xml xml ) as begin INSERT INTO pizza_xml (LOC_CODE, CUST_CODE, PRODUCT_ID, INV_TYPE, INV_NO, INV_DT, INV_QTY_IN_INV_UOM, INV_RATE_IN_BS_CURR, INV_VU_IN_INV_CURR, -- TOTAL_DISC_IN_BS_CURR, NET_INV_VU_IN_INV_CURR, NET_INV_VU_IN_BS_CURR, TOTAL_TXES_IN_BS_CURR ) select table1.column1.value('@LOC_CODE','nvarchar(75)'), table1.column1.value('@CUST_CODE','nvarchar(75)'), table1.column1.value('@PROD_CODE','nvarchar(75)'), table1.column1.value('@INV_TYPE','nvarchar(50)'), table1.column1.value('@INV_NO','nvarchar(100)'), table1.column1.value('@INV_DT','datetime'), table1.column1.value('@INV_QTY_IN_INV_UOM','numeric(28,8)'), table1.column1.value('@INV_RATE_IN_BS_CURR','numeric(28,8)'), table1.column1.value('@INV_VU_IN_INV_CURR','numeric(28,8)'), --table1.column1.value('@TOTAL_DISC_IN_BS_CURR','numeric(28,8)'), table1.column1.value('@NET_INV_VU_IN_INV_CURR','numeric(28,8)'), table1.column1.value('@NET_INV_VU_IN_BS_CURR','numeric(28,8)'), table1.column1.value('@TOTAL_TXES_IN_BS_CURR','numeric(28,8)') from @xml.nodes('pizza/pizzaxml')as table1(column1) end declare @id

can alias in select be used for selecting other column in that table?

Hi All,I want to use an alias name in a select clause to select other column in that table? select   top 1 (   case when CreatedByName <> '' then 'yy'         else 'xx' end) as filName, (filName + 'xx')from Order       But it throws error like " Invalid column name 'fileName'."Could you please help me out?

create and insert into a dynamic sql table at runtime

Below I have a bunch of SQL statements that creates a table at runtime and the "pic" column is a dynamic column and the code creates the number of "pic" columns depending on the count of the uploader control.  the problem comes when I try to insert into that table and I am trying to say for every "pic" declare variable @pic.... it works well for just one file in the uploader but for multiple files i get the following error The name "pic1" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.Directory.CreateDirectory(MapPath(".") & "\port\" & clientname.Text & "\")        Dim objConn As New SqlConnection("Data Source=xxxxxxxxx.hostedresource.com; Initial Catalog=mrpoteat; User ID=xxxxxxx; Password=xxxxxxxxx;")        objConn.Open()        Dim strCommandText As String = ""        For index = 1 To Attachments1.Items.Count Step 1            If String.IsNullOrEmpty(strCommandText) Then                strCommandTex

How to insert the Current date and time in to SQL Table..

Hello Members,              I have create the table as per the following ..create table company(  empname varchar(30),  empid int,  joindate smalldatetime)I tried,insert into table values('Kumar',202, ??????)I want to insert Current date and time into table Company.....Please give me the solution...Thanks.. 

pull data from table A and insert into the same table

Hi All, When I pull data from one table and try to insert into the same table, is it possible for any erroneous data loading? ex:   Insert Into TableA Select Cat,Bank, City, Act From TableA A CROSS APPLY (SELECT COUNT(ACT) AS TOT from TableA ) B   Thanks        shamen
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend