T-SQL (SS2K8) :: How To Insert Queries In A Table

Feb 9, 2015

I am trying to insert the queries in a table such as the following, not able to insert it.

create table test (txt Varchar(200))
insert into test values('select *from master.dbo.sysprocesses WHERE status NOT IN('sleeping','background')')

View 4 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Stored Procedure To Truncate And Insert Values In Table 1 And Update And Insert Values In Table 2

Apr 30, 2015

table2 is intially populated (basically this will serve as historical table for view); temptable and table2 will are similar except that table2 has two extra columns which are insertdt and updatedt

process:
1. get data from an existing view and insert in temptable
2. truncate/delete contents of table1
3. insert data in table1 by comparing temptable vs table2 (values that exists in temptable but not in table2 will be inserted)
4. insert data in table2 which are not yet present (comparing ID in t2 and temptable)
5. UPDATE table2 whose field/column VALUE is not equal with temptable. (meaning UNMATCHED VALUE)

* for #5 if a value from table2 (historical table) has changed compared to temptable (new result of view) this must be updated as well as the updateddt field value.

View 2 Replies View Related

T-SQL (SS2K8) :: Insert Causing Delay From Table To Table

Oct 28, 2014

I am trying to move data from one table to the another (staging to real time) in a stored procedure.

There are no indexes or primary keys on the target table and it is still taking ages to execute it (30 minutes approx.). There are no defaults, no constraints as well. There is one identity int column though.

There are some 500000 odd rows in the target table.

I am using the

Insert into..
Select from..

method.

View 2 Replies View Related

T-SQL (SS2K8) :: Insert Subset Of Self-referencing Table Into That Table

Mar 19, 2015

IF OBJECT_ID('tTable') IS NOT NULL
DROP TABLE tTable
GO

CREATE TABLE tTable
(nRow_IdINTEGER IDENTITY NOT NULL PRIMARY KEY,
nParent_IdINTEGERNULL,

[Code] ....

gives:

nRow_Id nParent_Id cGroup cValue
----------- ----------- ------- ------
1 1 One A
2 1 One B
3 2 One C

I want to insert a copy of this data, but w/ group = 'TWO', so the table will contain the additional rows

4 4 Two A
5 4 Two B
6 5 Tow C

View 5 Replies View Related

T-SQL (SS2K8) :: Built Insert Statement Into Table

Nov 1, 2015

I've 2 tables as follow, --> Full script and data as attachment, Scripts.zip

CREATE TABLE [dbo].[myMenuCollection](
[menuCollection_idx] [int] NOT NULL,
[parentID] [int] NULL,

[code]....

You can see - User select 3 Menu, which is the Menu Id is 1, 4, 10.If the Parent Id for Menu is 0, there is 1 record only to insert. If the Parent Id for Menu != 0, we've to make sure the Insert statement will insert the Parent Menu automatically

Based on Photo Above, there's 3 Menu is selected. But, in back-end - Insert statement will insert 4 record. Please see Menu Id = 10. The Parent Id = 9. So, we need to insert Menu Id = 9 automatically into myInsertedMenu table

View 4 Replies View Related

T-SQL (SS2K8) :: MERGE Insert Not Working Into Target Table

Mar 16, 2014

I am trying to insert new records into the target table, if no records exist in the source table. I am passing user specific values for insert, but it does not insert any values, nor does it throw any errors. The insert needs to occur in the LOAN_GROUP_INFO table, i.e. the target table.

MERGE INTO LOAN_GROUP_INFO AS TARGET
USING (SELECT LGI_GROUPID FROM LOAN_GROUPING
WHERE LG_LOANID = 22720
AND LG_ISACTIVE = 1)
AS SOURCE

[Code] .....

View 8 Replies View Related

T-SQL (SS2K8) :: Use Stored Procedure Result To Insert Into Table

Mar 25, 2015

My stored procedure returns one row. I need to insert the result to a table. Can I right something like that:

=============
Insert into table1
exec myProc '1/1/15', 3/1/15'
=====

Or may be I can use Table-valued function insted of myProc?

View 4 Replies View Related

T-SQL (SS2K8) :: Combine 2 Selects - Insert Results In Two Columns Of New Table

Sep 11, 2014

DECLARE @EmployeeID nvarchar(1000)
DECLARE @FiscalYear nvarchar(1000)

SET @EmployeeID = '101,102,103,104,105'
SET @FiscalYear = '2013,2014'

SELECT Data FROM dbo.Split(@EmployeeID, ',')
SELECT Data FROM dbo.Split(@fiscalyear, ',')
_______________________________________

This is part of a bigger project but I am stuck on this part. I get back 2 result sets

Data Data
101 2013
102 2014
103
104
105

I want to insert the results in a new table 2 columns and get the results below.

New Table
ID Fiscal Year
101 2013
101 2014
102 2013
102 2014
103 2013
103 2014
104 2013
104 2014
105 2013
105 2014

View 2 Replies View Related

Insert / Update In Master Table And Also Save A History Of Changed Records : Using Data Flow/simple Sql Queries

Feb 9, 2007

Hi,

My scenario:

I have a master securities table which has 7 fields. As a part of the daily process I am uploading flat files into database tables. The flat files contains the master(static) security data as well as the analytics(transaction) data. I need to

1) separate the master (static) data from the flat files,

2) check whether that data is present in the master table, if not then insert that data into the master table

3) If data present then move that existing record to an history table and then update the main master table.

All the 7 fields need to be checked to uniquely identify a single record in the master table.

How can this be done? Whether we can us a combination of data flow items or write a sql procedure to do all this.

Thanks in advance for your help.

Regards,

$wapnil

View 4 Replies View Related

T-SQL (SS2K8) :: SSIS - Extract Data From Table And Insert In Message Body And Email To User

Jun 25, 2014

What I am trying to do, Extract the data from SQL table and Insert in Email Body and email to user. I got good article on Internet, I follow all steps as it is, but still I am getting error.

Here is the link : [URL] ....

But I am getting Error:

Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
at System.String.Format(IFormatProvider provider, String format, Object[] args)
at ST_7f59d09774914001b60a99a90809d5c5.csproj.ScriptMain.Main()

[Code] ....

View 4 Replies View Related

T-SQL (SS2K8) :: Indexing Tips For MIN And MAX In Queries

Jun 6, 2014

Are there any best practices for indexing to support queries with MIN() and MAX() in them? what if MIN() and MAX() are partitioned? Super bonus question: what if MIN() and MAX() are not only partitioned, but are called on a field in a derived table, and one of the partitioning elements comes from a table that's being joined in the derived table?

I experimented with inserting the derived table into a temp table, putting a POC index on that, and querying out, but that actually took longer.

View 9 Replies View Related

T-SQL (SS2K8) :: OPENQUERY Syntax To Insert Into Server Table From Oracle Linked Server

Aug 28, 2014

I was trying to figure out what the OPENQUERY Syntax is to Insert into SQL Server Table from Oracle Linked Server.

View 7 Replies View Related

T-SQL (SS2K8) :: Joining Results Of Two Queries Without Creating Temporary Tables?

Nov 16, 2014

In the T-SQL below, I retrieved data from two queries and I've tried to join them to create a report in SSRS 2008 R2. The SQL runs, but I can't create a report from it. (I also couldn't get this query to run in an Excel file that connects to my SQL Server data base. I've used other T-SQL queries in this Excel file and they run fine.) I think that's because I am creating temporary tables. How do I modify my SQL so that I can get the same result without creating temporary tables?

/*This T-SQL gets the services for the EPN download from WITS*/

-- Select services entered in the last 20 days along with the MPI number and program code.

SELECT DISTINCT dbo.group_session_client.note, dbo.group_session_client.error_note, dbo.group_session_client.group_session_id,
dbo.group_session_client.group_session_client_id, dbo.group_session.signed_note, dbo.group_session.unsigned_note
into #temp_group_sessions
FROM dbo.group_session_client, dbo.group_session
WHERE dbo.group_session_client.group_session_id = dbo.group_session.group_session_id

-- Select group notes

SELECT DISTINCT
dbo.client_ssrs.state_client_number, dbo.delivered_service_detail.program_name, dbo.delivered_service_detail.start_date,
dbo.delivered_service_detail.start_time,
dbo.delivered_service_detail.service_name, dbo.delivered_service_detail.cpt_code, dbo.delivered_service_detail.icd9_code_primary,

[code]....

-- Form an outer join selecting all services with any group notes attached to them.

select * from #temp_services
LEFT OUTER JOIN #temp_group_sessions
on #temp_services.group_session_client_id = #temp_group_sessions.group_session_client_id
;

-- Drop temporary tables

DROP TABLE #temp_group_sessions;
DROP TABLE #temp_services;

View 9 Replies View Related

T-SQL (SS2K8) :: Insert / Update Triggers When Insert Run Via Script

Oct 23, 2014

I'm working on inserting data into a table in a database. The table has two separate triggers, one for insert and one for update (I don't like it this way, but that's how it's been for years). When there is a normal insert, done via a program, it looks like the triggers work fine. When I run an insert manually via a script, the first insert trigger will run, but the update trigger will fail. I narrowed down the issue to a root cause.

This root issue is due to both triggers using the same temporary table name. When the second trigger runs, there's an error stating that a few columns don't exist. I went to my test server and test db and changed the update trigger so that the temporary table is different than the insert trigger temporary table, the triggers work fine. The weird thing is that if the temporary table already exists, when the second trigger tries to create the temporary table, I would expect it to fail and say that it already exists.I'm probably just going to update the trigger tonight and change the temporary table name.

View 1 Replies View Related

T-SQL (SS2K8) :: Insert Into Table Dates In Between Two Dates

Feb 28, 2015

I have a table that has hotel guests and their start stay date and end stay date, i would like to insert into a new table the original information + add all days in between.

CREATE TABLE hotel_guests
(
[guest_name] [varchar](25) NULL,
[start_date] [date] NULL,
[end_date] [date] NULL,
[comment] [varchar](255) NULL

[code]...

View 7 Replies View Related

Insert, Update Queries

Feb 11, 2004

Is there any way to use a graphical designer to build your insert & update SQL statements in Enterprise manager? I mean Access has an EASY way to build them, surely SQL does too?

I would just build them in Access and copy the SQL, but then I'm stuck replacing all the "dbo_" with "dbo." and other little nuances.

View 3 Replies View Related

Insert Into From 4 Select Queries

Oct 8, 2014

I have 4 tables which I am extracting 2 distinct values;

Select Distinct UniId, PID from dbo.Event1
Select Distinct UniId, PID from dbo.Event2
Select Distinct UniId, PID from dbo.Event3
Select Distinct UniId, PID from dbo.Event4

Then, I want to select Distinct between these 4 tables (Event1, Event2, Event3 and Event4)

Then insert the distinct records of the 4 tables to the final table - dbo.EventLookup .

View 2 Replies View Related

Insert With Multiple Sub Queries

May 27, 2008

In Sql 2005, I can't get this to work. I am getting an error that says SQL does not support subquery. SQL has a problem with my subquery. It works fine with one subquery, but adding multiple gives me an an error.


INSERT INTO STU_SUMMARY
(SUMMARY_PERIOD,
CHILD_COUNT, NO_DATA_ERRORS, PROG_CD_DESCREP, TOT_CURR_SPEDSTU)
VALUES (GETDATE(),
(select count(*) counter from DATA_ERROR_DETAIL),
(select count(*) counter from DATA_ERROR_DETAIL),
(select count(*) counter from DATA_ERROR_DETAIL),
(select count(*) counter from DATA_ERROR_DETAIL),
)

View 1 Replies View Related

Updating/Insert With Dataset Or Queries

Jun 1, 2007

Hi,Ive got a class in my code which contains data from several tables. A user profile has a single record in a user_profile tables, for each of these records there is several records in a another table, which itself has several records in a tags table.So far the save method on the class saves the record to the user profile table, then loops through the next two tables info to insert each record. I want to decrease the number of trips to the database and am wondering if anyone can advise on the best way to do this.I am considering using a dataset to retrieve and store the records, instead of a datareader Im using currently. Then when Im done altering the data in the dataset (all three tables) I can commit all the changes in one database transaction?? I have been avoiding datasets due to the fact datareaders are apparently faster.My other option is to try make three calls to the database, one per table, updating my stored procedures to accept arrays of data using XML?? Can anyone tell me what is the best option for me?Thanks,C 

View 5 Replies View Related

Combining PIVOT And INSERT Queries

Nov 21, 2007

Can someone please help me modify the following pivot query into an INSERT INTO query (i.e. results are exported into a new table)...
 SELECT RespondantID, [1] As Q1, [2] As Q2, [3] As Q3, [4] As Q4, [5] As Q5, [6] As Q6, [7] As Q7, [8] As Q8, [9] As Q9, [10]

As Q10 FROM (SELECT RespondantID, QuestionID, Answer FROM [3_Temp]

WHERE SurveyID=1) AS preData PIVOT

( MAX(Answer) FOR QuestionID IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10]) )

AS data

ORDER BY RespondantID
 
Thanks,
Martin

View 1 Replies View Related

Problems With Two Insert Queries In A Page

Feb 22, 2005

Hello

I have a question about something odd happening with an insert query.

I am working on a password protected site and I want to moniter general student use. I have an on page load even which picks up their user id and the url and sends it to the database

Because my site is a beta site, I also want the users to be able to add their comments as and when they want, so I built a small feedback form on each page.

The quick feedback form has a panel to hide it until a user clicks on a radio button and this reveals a text box and a submit button.

However, since I have added this second sql connection with an insert, I now get an error message I was getting a connection string error when I tried to point at the connection string in the web.config file, so I put the full path in to the database and now I get an error message that says the conTrackUser has not been declared, but as you can see from the code it certainly has. So I'm beginning to thing that the error is something entierly different, but that's probably me being thick.

I've pasted the two insert blocks below, I can't see anything wrong with them, but then I'm mostly groping about in the dark with asp.net.

Is it not possible to have two insert commands on a page? That would be daft.

Here is the code.

Track and initilize the radio button and panel for the feedback:


Sub Page_Load(Sender As Object, E As EventArgs)
Dim UserID as String = session("UserID")
pnlQuickFeedback.Visible = False
If Not Page.IsPostback Then
Dim conTrackUser As SqlConnection
Dim strInsert As String
Dim cmdInsert As SqlCommand

conTrackUser = New SqlConnection("server='server'; user id='me'; password='nuts'; database='database'")

cmdInsert = New SqlCommand("TrackUser5530", conTrackUser)
cmdInsert.CommandType = CommandType.StoredProcedure
cmdInsert.Parameters.Add("@UserIdentity", session("UserID") )
cmdInsert.Parameters.Add("@URL", Request.Url.AbsoluteUri )

conTrackUser.Open()
cmdInsert.ExecuteNonQuery()
conTrackUser.Close()
End If
End Sub

The sub for the feedback:

Sub SubmitFbbtn_Click(Sender As Object, E As EventArgs)
Dim UserID as String = session("UserID")


'If Not Page.IsPostback Then
Dim conQuickFeedback As SqlConnection
Dim strInsert As String
Dim cmdInsert As SqlCommand

conQuickFeedback = New SqlConnection("server='server'; user id='me'; password='nuts'; database='database'")

cmdInsert = New SqlCommand("QuickComments5530", conQuickFeedback)
cmdInsert.CommandType = CommandType.StoredProcedure
cmdInsert.Parameters.Add("@UserIdentity", session("UserID") )
cmdInsert.Parameters.Add("@Comments", txtComments.text)
cmdInsert.Parameters.Add("@URL", Request.Url.AbsoluteUri )

conQuickFeedback.Open()
cmdInsert.ExecuteNonQuery()
conQuickFeedback.Close()
pnlQuickFeedback.Visible = False
feedbackFormbtn.Visible = True
feedbackFormbtn.Checked = False
End Sub

thanks

View 1 Replies View Related

Increasing Performance On Insert Queries

Mar 5, 2001

Does anyone know how to improve performance on insert statements. I have to run a query of several thousand insert statements, but it just takes too long. Does anyone know of any good tips to improve performance?

joe

View 3 Replies View Related

SQL Stored Procedure Can't Insert , Parameterized Queries...

May 16, 2004

I have a SQL stored procedure like so:

CREATE PROCEDURE sp_PRO
@cat_num nvarchar (10) ,
@descr nvarchar (200) ,
@price DECIMAL(12,2) ,
@products_ID bigint
AS
insert into product_items (cat_num, descr, price, products_ID) values (@cat_num, @descr, @price, @products_ID)


when I try and insert something like sp_PRO '123154', 'it's good', '23.23', 1

I can't insert "'" and "," because that is specific to how each item is delimited inorder to insert into the stored procedure. But if I hard code this into a aspx page and don't create a stored procedure I can insert "'" and ",". I have a scenario where I have to use a stored procedure...confused.

View 3 Replies View Related

Select, Insert And Delete Queries Timing Out

Jul 20, 2005

I am using a sql server 2000 database to log the results from a monitorthat I have running - essentially every minuite, the table describedbelow has a insert and delete statements similar to the ones below runagaint it.Everything is fine for a few weeks, and then without fail, all accessesto the table start slowing down, to the point where even trying toselect all rows starts timing out.At that point, the only way to make things right that I have found, isto delete the table and recreate it.Am I doing something specific that sql server really doesn't like? Isthere a better solution then deleting and recreating the table?CREATE TABLE [www2] ([ID] [int] IDENTITY (1, 1) NOT NULL ,[stamp] [datetime] NULL CONSTRAINT [DF_www2_stamp] DEFAULT (getdate()),[success] [bit] NULL ,[report] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[level] [int] NULL ,[iistrace] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]GOINSERT INTO [www2] ([Report],[Success],[Level],[iistrace],[Stamp])VALUES ('Error on: <ahref="http://www2.klickit.com/include/asp/system_test.asp">http://www2.klickit.com/include/asp/system_test.asp</a><br><br>The operation timedout<br><br>(Test Activated From: Lynx/2.8.2rel.1libwww-FM/2.14)',0,1,'',getDate())DELETE FROM [www2] WHERE (Stamp<getDate()-3) AND (Success=1) AND (ReportNot Like 'ResetThanks in advance,Simon Withers*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 1 Replies View Related

Performing Insert / Update Queries Using Pocket PC / SQL CE

Sep 8, 2007

I'm writing an application for Windows Mobile 5 / Pocket PC using VB.NET 2005. The database is connected using an instance of SqlCeConnection and updated by an SqlCeCommand.

The application can perform select queries on data originally entered into the database through Visual Studio, or perform update / insert queries at run time. Anything inserted or updated can be returned by a select query whilst the application is running, however, anything I have inserted or updated doesn't appear to be written to the SDF file and hence is not in the database after restarting the application.

Am I missing something that's different between performing queries on an SQL CE database on Pocket PC and an ODBC source in a normal Windows application?

View 13 Replies View Related

T-SQL (SS2K8) :: INSERT Only When Value Has Been Updated?

Oct 14, 2014

I have database that holds column depicting various events and the last time that the event occurred.I query the database and I get a result like this:

Event Update Time
Event A 2014-10-14 00:35:00.000
Event B 2014-10-14 01:30:00.000
Event C 2014-10-14 00:35:00.000

Event L 2100-01-01 00:00:00.000..I would like to create another database to hold the various timestamps for each event. Some of these events happen every 2 minutes, others hourly, daily or monthly.I can query the source every minute. I do not want duplicate entries in the destination when the 'Update Time' has not been updated. Is it better to query the destination for the latest 'Update Time' value and only INSERT the new record when the time has been updated or just put a UNIQUE constraint on the Event and UpdateTime columns?

View 9 Replies View Related

T-SQL (SS2K8) :: Eliminating Duplicates While Insert?

Apr 10, 2014

WITH cte_OrderProjectType AS
(
select Orderid, min(TypeID) , min(CTType) , MIN(Area)
from tableA A inner join
tableB B ON A.PID = B.PID left join
tableC C ON C.TypeID = B.TypeID LEFT JOIN
tableD D ON D.AreaID = B.ID
group by A.orderid
)

This query uses min to eliminate duplicates. It takes 1.30 seconds to complete..

Is there any way I can improve the query performance ?

View 9 Replies View Related

T-SQL (SS2K8) :: How To Insert Or Update Primary Key (int)

May 22, 2014

since ten years perhpas the society has a database with some table (person, country, and so on)since last years , the project manager decides to create a new database with some new design because before some information was save in one table well, the problem is when we pass all application to the new model we've notice that some id are not the same !

sample :

table Language old model
-------------------------
id frenchDescription english description
----------------------------------------
3 Anglais English
.....
......

table Language new model

id frenchDescription english description
-----------------------------------------
5 Anglais English
.....
.....

Alright , you can understand that the new model must be the same id => 3

my question is how to modify id on the table ?

View 4 Replies View Related

T-SQL (SS2K8) :: After Insert Or Update Trigger

Jul 11, 2014

I currently have a AFTER UPDATE trigger that looks at a specific column being updated. It works great, but I am now needing to also capture the field data when it is initially created as well. Do I need to build a sperate FOR INSERT trigger to capture the initial column data when inserted, or is it possible to build it into my current AFTER UPDATE trigger?

Here is my current trigger:
CREATE TRIGGER [dbo].[xResponsible_By] ON [dbo].[PARTS_REQUESTOR]
AFTER UPDATE

[code]....

View 2 Replies View Related

T-SQL (SS2K8) :: Compare And Insert Record

Oct 15, 2014

I am having below two tables:

1) TableA : Which contains 5 columns(Column1,..........Column5)
2)TableB : Which contains 10 columns(Column1,..........Column10)

TableB contains millions of data.Now I want select all 5 columns from tableA but combination of Column1,Column2,Column3 if present in tableB, then i want exclude that records.I am doing as below:

select * from TableA a join TableB b a.column1!=b.column1 and a.column2!=b.column2 and a.column3!=b.column3 )

But query is taking almost 5 minutes. Is there is another approach?

View 4 Replies View Related

T-SQL (SS2K8) :: Insert Value Generate Special Character

Mar 12, 2014

I have a web page where the user can select the language (FR, EN, BG, ...) in a drop down list.

Next to the drop down list there is a text box where user can type the some text (translation).

User can add several description

On my web page, i have a button this button collect all information create an xml file and save all in database (sql server 2008)

that's work fine for some language => FR, EN and so on

But for bulgarian (bulgare) and greece there are some problem...

Some characters when i display it in sql look like => ???s??. ? d??ta?? a?t?

The value encoded by the user is => Ένωσης. Η διάταξη αυτή

but the result after t sql xpath is => ???s??. ? d??ta?? a?t?

Here is it my sql code where you can find my temporary table and my xml file and my xpath query

declare @tblTranslation table (idDocID int, languageID varchar(10), value varchar(500))
declare @Translations XML

set @Translations = '<?xml version="1.0" ?><Items><Item><eleKey>EN</eleKey><eleValue>This is a test</eleValue></Item><Item><eleKey>FR</eleKey><eleValue>test</eleValue></Item><Item><eleKey>BG</eleKey><eleValue>Ένωσης. Η διάταξη αυτή</eleValue></Item><Item><eleKey>HR</eleKey><eleValue></eleValue></Item><Item><eleKey>RO</eleKey><eleValue></eleValue></Item></Items>'

-- 2) fill the temporary table with information from the xml file

INSERT INTO @tblTranslation(idDocID, languageID, value)
SELECT
1
, Convert(nvarchar(max), i.query('eleKey/text()')) as colKey
, Convert(nvarchar(max), i.query('eleValue/text()')) as colValue
--
FROM @translations.nodes('/Items/Item') as x(i)
SELECT * FROM @tblTranslation

View 3 Replies View Related

T-SQL (SS2K8) :: Selection With Conditional Insert Union

Apr 4, 2014

In this selection when there is particular segment found in the selection then need to add 2 records per segment otherwise just selected results

--Drop table #list
CREATE TABLE #LIST ( email varchar(20),Segment varchar(20), Addr1 varchar(20), City varchar(20),ST varchar(20), Code int)
--Drop table #subject
CREATE TABLE #Subject (Segment varchar(20), Fname varchar(20), LName varchar(20))

[Code] ....

---Selection results
SELECT L.Segment , l.email, l.Addr1 , l.City ,l.ST, l.code, s.Fname , s.LName into #expectedresult FROM #LIST L JOIN #Subject S ON l.Segment =s.Segment

--Now here what i am trying to get, union the below two record to the above "selection Results" for only segment ='VEC_BAL' or segment = 'PPC_BAL'

--2 records
SELECT l.segment , l.email , Addr1, City, ST, 999 as Code,'' fname, ''lname from #LIST l where email ='mmm@m.com'
SELECT l.segment , l.email , Addr1, City, ST, 888 as Code, '' fname, ''lname from #LIST l where email ='lrk@m.com'

--- expected results please execute below block ( per each segment 2 records will insert if there is segment ='VEC_BAL' or 'PPC_BAL' ). If there is no Vec_Bal or PPC BAL then no additional inserts, if there is only VEC_BAL no PPC_BAL then only 2 records insert
SELECT L.Segment , l.email, l.Addr1 , l.City ,l.ST, l.code, s.Fname , s.LName into #expctresults1 FROM #LIST L JOIN #Subject S ON l.Segment =s.Segment
union

[Code] .....

View 3 Replies View Related

T-SQL (SS2K8) :: Trying To Build A Stored Procedure With Insert Into

Apr 9, 2014

OK, to simplify some annual auditing of DB users (not the SQL logins,) I'm trying to craft a stored procedure that the customer on the server (they're the only customer on this particular server) can run to get a listing of all DB users and what roles they have.

I've got a query that returns this for the currently selected DB, so that part's done.I can use SP_MSFOREACHDB to run it against each DB, with the results going into a temp table to make it easier to copy/paste into an Excel file.What I want to do, and can't seem to see how, is wrap the whole thing in yet another SP of my own, with an EXECUTE AS so that the customer doesn't need sysadmin or any special privileges on the server. When I do this, it runs, but only against master.

Now, from digging it looks like you can't have an "insert #temptable exec sp_whatever" inside another SP. I'd like to avoid dynamic SQL, and while I know there are problems with MSFOREACHDB, it'll work for what we need.how to turn a user created SP, into a system SP so it can be run regardless of the DB you've selected, so at least there's that.

View 7 Replies View Related







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