This is an ugly duck query but it seems to work fine. when I try to directly execute the remote stored procedure such as with
insert into query_log exec remoteServer.master.dbo.##up_fetchQuery
I get execution error
Server: Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure '##up_xportQueryLog'.
Database name 'master' ignored, referencing object in tempdb.
When I try
insert into query_log exec remoteServer.tempdb.dbo.##up_fetchQuery
I get
Server: Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure '##up_xportQueryLog'.
Database name 'tempdb' ignored, referencing object in tempdb.
with
insert into query_log exec remoteServer..dbo.##up_fetchQuery
or
insert into query_log exec remoteServer...##up_fetchQuery
I get
Server: Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure '##up_xportQueryLog'.
I guess the remote server has trouble resolving the name of the global temp stored procedure when its reference comes in as a remote stored procedure calls. Is there any way to directly call a global temp stored procedure from a remote server or do I need to stick with this goofy-looking work-around?
hi,I wish to create a temporary table who's name is dynamic based on theargument.ALTER PROCEDURE [dbo].[generateTicketTable]@PID1 VARCHAR(50),@PID2 VARCHAR(50),@TICKET VARCHAR(20)ASBEGINSET NOCOUNT ON;DECLARE @DATA XMLSET @DATA = (SELECT dbo.getHistoryLocationXMLF (@PID1, @PID2) as data)CREATE TABLE ##@TICKET (DATA XML)INSERT INTO ##@TICKET VALUES(@DATA)ENDis what i have so far - although it just creates a table with a name of##@TICKET - which isn't what i want. I want it to evaluate the name.any ideas?
I have an sql file that contains several queries that are generating numbers to populate a sql table. The sql file is too large for a single sp so I am nesting them. I have 4 nested stored procedures. Each of the queries in each stored procedure dumps into its own global temp table. The final stored procedure needs to insert into a sql table all the information gathered in the global temp tables. So the final stored proc. looks something like: "Create procedure usp_myProc_4 AS EXEC usp_myProc_3 INSERT INTO mySQLTable (a,b,c) SELECT a, b, c FROM ##myTempTable (which was created in usp_myProc_1)
INSERT INTO mySQLTable (a,b,c) SELECT a, b, c FROM ##myOtherTempTable
INSERT INTO......etc;"
I have done this befor and it worked fine. The only difference is that when I did this before these insert statements were being called from within an sp_makewebtask procedure.
Now when I try to save this final stored procedure it tells me "Invalid Object Name: ##myTempTable"
How do I call on these global temp tables from my final nested stored procedure?
Looking at BOL for temp tables help, I discover that a local temp table (I want to only have life within my stored proc) SHOULD be visible to all (child) stored procs called by the papa stored proc.
However, the following code works just peachy when I use a GLOBAL temp table (i.e., ##MyTempTbl) but fails when I use a local temp table (i.e., #MyTempTable). Through trial and error, and careful weeding efforts, I know that the error I get on the local version is coming from the xp_sendmail call. The error I get is: ODBC error 208 (42S02) Invalid object name '#MyTempTbl'.
Here is the code that works:SET NOCOUNT ON
CREATE TABLE ##MyTempTbl (SeqNo int identity, MyWords varchar(1000)) INSERT ##MyTempTbl values ('Put your long message here.') INSERT ##MyTempTbl values ('Put your second long message here.') INSERT ##MyTempTbl values ('put your really, really LONG message (yeah, every guy says his message is the longest...whatever!') DECLARE @cmd varchar(256) DECLARE @LargestEventSize int DECLARE @Width int, @Msg varchar(128) SELECT @LargestEventSize = Max(Len(MyWords)) FROM ##MyTempTbl
SET @cmd = 'SELECT Cast(MyWords AS varchar(' + CONVERT(varchar(5), @LargestEventSize) + ')) FROM ##MyTempTbl order by SeqNo' SET @Width = @LargestEventSize + 1 SET @Msg = 'Here is the junk you asked about' + CHAR(13) + '----------------------------' EXECUTE Master.dbo.xp_sendmail 'YoMama@WhoKnows.com', @query = @cmd, @no_header= 'TRUE', @width = @Width, @dbuse = 'MyDB', @subject='none of your darn business', @message= @Msg DROP TABLE ##MyTempTbl
The only thing I change to make it fail is the table name, change it from ##MyTempTbl to #MyTempTbl, and it dashes the email hopes of the stored procedure upon the jagged rocks of electronic despair.
Any insight anyone? Or is BOL just full of...well..."stuff"?
I have a stored proc that creates a global temp table. How can I have multiple users select records from and insert records in that table without overwriting and/or deleting data?
Using a string of IDs passed into a stored procedure as a VARCHAR parameter ('1,2,100,1020,') in an IN without parsing the list to a temp table or table variable. Here's the situation, I've got a stored procedure that is called all the time. It's working with some larger tables (100+ Million rows). The procedure passes in as one of the variables a list of IDs for the large table. This list can have anywhere from 1 to ~100 IDs passed to it.
Currently, we are using a function to parse the list of IDs into a temp table then joining the temp table to get the query:
CREATE PROCEDURE [dbo].[GetStuff] ( @IdList varchar(max) ) AS SET NOCOUNT ON SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
[Code] .....
The problem we're running into is that since this proc gets called so often, we sometimes run into tempDB contention that slows this down. In my testing (unfortunately I don't have a good way of generating a production load) swapping the #table for an @table didn't make any difference which makes sense to me given that they are both allocated in the tempDB. One approach that I tried was that since the SELECT query is pretty simple, I moved it to dynamic SQL:
CREATE PROCEDURE [dbo].[GetStuff] ( @IdList varchar(max) ) AS SET NOCOUNT ON SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
[Code] ....
The problem I had there, is that it creates an Ad Hoc plan for the query and only reuses it if the same list of parameters are passed in, so I get a higher CPU cost because it compiles a plan and it also causes the plan cache to bloat since the parameter list is almost always different. Is there an approach that I haven't considered that may get the best of both worlds, avoiding or minimizing tempDB contention but also not having to compile a new plan every time the proc is run?
Is it possible to check query execution plan of a store procedure from create script (before creating it)?
Basically the developers want to know how a newly developed procedure will perform in production environment. Now, I don't want to create it in production for just checking the execution plan. However they've provided SQL script for the procedure. Now wondering is there any way to look at the execution plan for this procedure from the script provided?
I am replicating a stored procedure execution, which builds and executes the following dynamic SQL command:
IF EXISTS (select * from MyDB..sysfiles sf (nolock) where name = 'MyDB_201201') ALTER DATABASE [MyDB] REMOVE FILE [MyDB_201201] IF EXISTS (select * from MyDB..sysfilegroups sfg (nolock) where groupname = 'MyDB_201201' and sfg.groupname not in( SELECT distinct fg.name file_group_name
[Code] ....
I can run this SP with no errors on both the publisher and the subscriber. However, when I try to replicate the execution of this SP, I get an error in replication monitor:
ALTER DATABASE statement not allowed within multi-statement transaction. (Source: MSSQLServer, Error number: 226)
How can I change my code to workaround this? Perhaps some explicit transactions?
I ma using sql server 2005.I have a bunch of statements of sql and i have created a stored procedure for those. When i execute i found that there is lot's of difference between execution time of stored procedure and direct sql in query windows.
can anyone help me to optimize the execution time for stored prcedure even stored prcedure is very simple. I have used sql server 2000 and i am new in sql server 2005.
Hi, I was wondering is anyone can help me out on this one, I want to run a query, but I need to reference a Database that exists on a different server. I am using SQL 6.5 Any suggestions would be welcomed, Thanks a mill, Fin
Has anyone encountered cases in which a proc executed by DTS has the following behavior: 1) underperforms the same proc when executed in DTS as opposed to SQL Server Managemet Studio 2) underperforms an ad-hoc version of the same query (UPDATE) executed in SQL Server Managemet Studio
What could explain this?
Obviously,
All three scenarios are executed against the same database and hit the exact same tables and indices.
Query plans show that one step, a Clustered Index Seek, consumes most of the resources (57%) and for that the estimated rows = 1 and actual rows is 10 of 1000's time higher. (~ 23000).
The DTS execution effectively never finishes even after many hours (10+) The Stored procedure execution will finish in 6 minutes (executed after the update ad-hoc query) The Update ad-hoc query will finish in 2 minutes
A regular permanent table is not an option: Need to exec a procA which at the end also exec procB.
procA will insert to table A and also generate a intermidate result set to a ##A global table, it works fine at this point. However, when it exec the procB at the end of exec procA, the ##A global table is empty when entering procB.
The key is I want to pass a records set to the procB without using a tableTempB. Does a ## global table should be still alive until procB execution is done?
I also tried use table variable, but it does not look like to accept @tableA as part of the procB's parameters.
Also tried function, but it could not support a #tempTable within it which will do a dynamic query insertion.
I am creating an sp, in which I check for the existence of a global temp table (using the exists) statement. If the Exists returns a false, I move on to processing without the temp table. If it returns a true, I utilize the temp table to do some inserts. I create the temp table when my application first starts up. The problem that I am facing is that the check for the temp table`s existence seems to be failing. Is there any other way to check for the existence of a global temp table??
I want to create several global temp tables. I've created a script:
if not object_id('tempdb..##tbl_ProductTypes') is null begin drop table ##tbl_ProductTypes end select * into ##tbl_ProductTypes from dbo.tbl_ProductTypes
This script creates a global temp table. When I run it in QA the table is created. When I close QA the table is dropped. This is correct since I found the following in BoL: [Global temporary tables are automatically dropped when the session that created the table ends and all other tasks have stopped referencing them. The association between a task and a table is maintained only for the life of a single Transact-SQL statement. This means that a global temporary table is dropped at the completion of the last Transact-SQL statement that was actively referencing the table when the creating session ended.]
I created a job that executes the statement above. The job exists with success, however the table is not created!
I have a pivot table implementation, part of which is posted below. Itreturns no errors in query analyzer, but when profiler is run, it showsthat "Error 208" is happening. I looked that up in BOL and it meansthat an object doesn't exist. This block of code below works fine on mylocal development machine, but not on our shared development serveruntil I go into the tempdb and make the user have the role db_owner.Even wierder is that when I do a select * from ##pivot there is noerror, but if I specify the single column name (pivot) i.e. selectpivot from ##pivot, it takes the error...Obviously this is a rights issue, but is there any way around thisother than making the user owner of tempdb??declare @select varchar(8000), @PackageId intset @PackageId = 10set @select = 'selectCompany = COALESCE(Users.Company, Contact.Company, ''''),SubContractPackageVendor.Id, SubContractPackageVendor.isActive,SubContractPackageVendor.isAwarded,SubContractPackageVendor.UserOrContactType,SubContractPackageVendor.UserOrContactIdFROMSubContractPackageVendorLEFT JOIN SubContractPackage ON SubContractPackageVendor.PackageId =SubContractPackage.IdLEFT JOIN Users ON UserOrContactType = ''User'' AND UserOrContactId =Users.UserIdLEFT JOIN UserRoles ON UserOrContactType = ''User'' ANDUserRoles.UserId = Users.UserId AND UserRoles.ProjectId =SubContractPackage.ProjectIdLEFT JOIN Role ON Role.RoleId = UserRoles.RoleIdLEFT JOIN Contact ON UserOrContactType = ''Contact'' ANDUserOrContactId = Contact.IdLEFT JOIN SubContractLineItem ONSubContractLineItem.RefType = ''Package'' ANDSubContractLineItem.RefId = SubContractPackageVendor.PackageIdLEFT JOIN SubContractLineItem as SubContractPackageVendorItem ONSubContractPackageVendorItem.RefType = ''PackageVendor'' ANDSubContractPackageVendorItem.RefId = SubContractPackageVendor.Id ANDSubContractPackageVendorItem.RefSubId = SubContractLineItem.IdWhereSubContractPackageVendor.PackageId = ' + CAST(@PackageId as varchar)+ 'GROUP BYSubContractPackageVendor.Id, SubContractPackageVendor.isActive,SubContractPackageVendor.isAwarded, Users.Company, Contact.Company,SubContractPackageVendor.UserOrContactType,SubContractPackageVendor.UserOrContactId'--print @sqldeclare @sumfunc varchar(100),@pivot varchar(100),@table varchar(100),@FieldPrefix varchar(5),@TotalFieldName varchar(50),@PivotFieldFilter varchar(1000)select@sumfunc ='Sum(isnull(SubContractPackageVendorItem.Total,0) )' ,@pivot ='SubContractLineItem.Category' ,@table ='SubContractLineItem' ,@FieldPrefix='~' ,@TotalFieldName = 'Total' ,@PivotFieldFilter = ' AND RefType=''Package'' AND RefId=' +CAST(@PackageId as varchar)set nocount onDECLARE @sql varchar(8000), @delim varchar(1), @TotalSql varchar(8000)SET NOCOUNT ONSET ANSI_WARNINGS OFFEXEC ('SELECT ' + @pivot + ' AS pivot INTO ##pivot FROM ' + @table + 'WHERE 1=2')EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @pivot + ' FROM ' +@table + ' WHERE '+ @pivot + ' Is Not Null ' + @PivotFieldFilter)SELECT @sql='', @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )SELECT @delim=CASE Sign( CharIndex('char',data_type)+CharIndex('date', data_type) )WHEN 0 THEN '' ELSE '''' ENDFROM tempdb.information_schema.columnsWHERE table_name='##pivot' AND column_name='pivot'select * from ##pivotDROP TABLE ##pivot
Can anyone tell me or post a link that says how many global temptables can exist SQL Server 2000? Also, is there a limit to thenumber of local temp tables that can exist?Thanks,Billy
I have two global temp tables in my stored procedure.Is it possible for me to make the execution of a stored procedure dynamic. Based on a flag parameter value I should get the result set from first temp table and viceversa ex: If my flag is 0.I should be able to get the result set from ##temp1 (select * from ##temp1).If my flag is 1.I should be able to get the result set from ##temp2 (select * from ##temp2).
In my stored procedure I need to select some data columns and insert them into a #temp tbl and then select the same data columns again using a different from and put them into the same #temp tbl. It sounds like a union, can I union into a #temp tbl? Any help here is appreciated.
How do I assign a temp value to a parameter in a stored procedure? I am trying like so: Alter PROCEDURE ap_Insert_Pricing_ListPrice @partNumber varchar = "CQ2"AS SELECT PartNumber FROM Pricing WHERE (PartNumber = @partNumber)GO What is the correct way to assign a temp value for testing purposes in SQL Server 2000 Query Analyzer? When I try: Alter PROCEDURE ap_Insert_Pricing_ListPrice @partNumber varchar AS Set @partNumber = "10-AF40-N04B-JZ"SELECT PartNumber FROM Pricing WHERE (PartNumber = @partNumber)GO I get error: Invalid column name '10-AF40-N04B-JZ'.
I need to select and mark 150 records at a time in a large table.What I'm trying to do is...Select top 150 xxxx into #temp from largeTableupdate largeTable set marked = 1 where xxxx in #tempThis is very simplified, the real procedure is quite large.The Error I am getting isInvalid object name '#temp'.
I'm pretty new with temp tables, i have this code that works fine as a normal query . but i want to put it in a stored procedure, so i can use it more then one. What do i need to change in the code for this to work. I also wanted to add to parematers to it. I know how to do parameters in stored procedures, but im more worried about getting this code in a stored procedure. any help will be greatly appreciated.
Code Snippet
USE fssrc SET NOCOUNT ON SELECT cr.sales_entity_code 'Territory' , sp.name 'SE', Date = CONVERT(char(12),DATEADD(day, (qh.cycle_day-1), p.start_date),6), qh.entity_code 'Customer', c.name 'Name', c.address2 'Address2', c.post_code 'PostCode', q.question_code 'Question Code', q.description 'Question', qt.description 'Response Type', qh.response 'Response' INTO #results FROM question_history qh, customer_relationship cr, sales_person sp, period p, questions q, customer c, question_type qt WHERE cr.customer_code = qh.entity_code AND qh.period_code = p.period_code AND sp.sales_entity_code = cr.sales_entity_code AND qh.question_code = q.question_code AND cr.customer_code = c.customer_code AND q.type_code = qt.type_code go SELECT distinct #results.* FROM #results ORDER BY #results.DATE, #results.territory, #results.se DROP TABLE #results
I have to extract data from a read only table using a globel temp table then export it to another OLE DB connection or to a flat file. But in the new SSIS packages it does not allow you to do thisusing the global ## symbols in front of a table name. How do I get around this?
I couldn't debug SQL Server by "Step into Stored Procedure" on Server Explorer of VS2008 (or VS2005) to SQL 2005 Developer on remote Windows Server 2003 machine, it allway issue exception "Unable to start T-SQL Debugging. Could not attach to SQL Server process on 'Server'. Click Help for more information"
1) The environment: The Client: Windows XP SP2 (WORKGROUP) Visual Studio 2008 (or VS2005)
The SQL Server Machine: Windows 2003 Server Sp1 (DOMAIN) SQL Server 2005 Developer
2) User account and Permission login: I create the same user account for both Client and Domain Server with the same password, i also add that user to "Administrators" group in both machine.
At the SQL Server on Server machine, i added that account to ServerSecurityLogin with 'sysadmin' role already
3) Connection and authentication: I used "Windows Authentication" for my connection to SQL server, and i checked sure my account of the connection by SQL command
SELECT SYSTEM_USER, IS_SRVROLEMEMBER ('sysadmin')
4) Firewall: I checked firewall like MSDN helping (i also tried to test by turn off firewall in both machine)
5) Visual Studio Remote Debugger: I read "How to: Enable SQL Server 2005 Debugging" on MSDN with comment "The SQL Server can run on the same machine as the application or on a remote machine. If you are debugging T-SQL code only, then no remote setup is required." so i didn't config Visual Studio Remote Debugger any thing.
Note: If i "Step Into Store Procedure" at Server locally, it works okey, so on at my PC client locally. But if i move debugging from my client to my Server, it occur error "Unable to start T-SQL Debugging. Could not attach to SQL Server process on 'Server'. Click Help for more information"???
If i execute store procedure on Server Explore, it works okey!
Could someone help me get this stored procedure to work? I want to give the stored procedure a long list of departments and have them added to a temp table. This only gets the first dept. in the temp table. I'm confused. Open to other suggestions, but want to use a 1col temp table to hold the depts.
After this is done, an SQL query is run using the temp table. Input for test: --csi_crystal_xxxx "pc9xp,pc8,pc7,pc6,pc6543,pc945678" --select * from ##CrystalGetCosts
create procedure csi_crystal_xxxx
@DeptResp varchar(4000) AS SET NOCOUNT ON DECLARE @SQL varchar(8000) DECLARE @Dept varchar(10) DECLARE @iLen int DECLARE @iPtr int DECLARE @iEnd int
If Exists (Select name, Type From [tempdb]..[sysobjects] where name = '##CrystalGetCosts' And Type = 'U') Drop table ##CrystalGetCosts
CREATE TABLE ##CrystalGetCosts (Dept_Resp_No varchar(10)) Set @iLen=Len(@DeptResp) Set @iPtr = 1 While @iPtr < @iLen BEGIN SET @iEND = charindex(',',@DeptResp,@iPtr) Set @Dept= Substring (@DeptResp,@iPtr,@iEnd-1) INSERT INTO ##CrystalGetCosts Values (@Dept) Set @iPtr = @iEnd + @iLen END
Hi I have a search page having four fields. Giving any one of the field as input should retrieve search results in Gridview. In GridView1 i have child Gridview for displaying details related to Gridview 1.
now i have to write storedprocedure for getting values in two grids. there is one matching column in two tables i.e CNo.from first select statement we have to capture CNo and basing on that retrieve second table values.
I have a stored procedure for that but my problem is i stored CNo in temp table i.e @MyTable .after doing select statements from two tables i want to delete @MyTable. But iam not able to. so pls help me
My stored procedure code is here:
set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go
ALTER PROCEDURE [dbo].[search1] (@val1 varchar(225), @val2 varchar(50), @val3 varchar(50), @val4 varchar(50)) AS BEGIN
DECLARE @MyTable table (CNo varchar(255))
INSERT @MyTable
Select CNo From customer where ((@val1 IS NULL) or (CNo = @val1)) AND ((@val2 IS NULL) or(LastName = @val2)) AND ((@val3 IS NULL) or(FirstName = @val3)) AND ((@val4 IS NULL) or(PhoneNumber = @val4))
--Now do your two selects
SELECT *
FROM customer c
INNER JOIN @MyTable T ON c.CNo = T.CNo
Select *
From refunds r
INNER JOIN @MyTable t ON r.CNo = t.CNo
END
The output of storedprocedure is like this:
Iam getting all the columns of two tables but the CNo column is repeating twice in both the tables. so please some one help me. The CNo colum shouldnot repeat.