Giving A Proc Database And Table Names As Parameters

Jan 10, 2007

Hello!

Is it possible to pass a stored procedure a parameter, say @table and
use it as a table in the sql command?
Finally i want a proc to copy tables from a database to another database.

THERE IS MY CODE:

CREATE PROCEDURE [user].[copytable]
@dbSRC varchar(100),
@dbTRGT varchar(100),
@table varchar(100)
AS

BEGIN TRANSACTION FreeAndCopyTable
TRUNCATE TABLE [@dbTRGT].admin.[@table]
INSERT INTO [@dbTRGT].admin.[@table]
SELECT *
FROM [@dbSRC].admin.[@table]

COMMIT TRANSACTION FreeAndCopyTable
IF @@error <0 GOTO E_Copy_Fail

E_Copy_Fail:
ROLLBACK TRANSACTION FreeAndCopyTable

GO

thanks in advance,
muh

View 2 Replies


ADVERTISEMENT

Variables For Table Names In Stored Proc

Nov 8, 2004

i'm trying to create a stored procedure that takes 2 input parameters (taken from a querystring): a table name, and a number that needs to be checked whether it exists within that table. yes, i have different tables, one for each forum, so they will have the same structures -- i'm figuring this approach will result in faster page-load times if the tables have less in them. if everyone here tells me that having one table for all the forums will work fine, i'll just go that route, but if not, here's my procedure:

Create Procedure VerifySubjectNum
(@forum_ID VARCHAR(10), @subject_num INT)
As
If Exists
(SELECT subject_num FROM @forum_ID WHERE subject_num = @subject_num)
Return 1
Else
Return 0

when i try to create this, i get an error saying @forum_ID must be declared... why doesn't it work within the select for the EXISTS?

View 6 Replies View Related

Parameters And Table Names

Sep 11, 2001

Please help,
I am inserting data into a newly created table with many rows similar to thoes below using a sp with a parameter @Extract
CREATE PROCEDURE mytest
@Extract int
AS
DECLARE @MyName varchar(25)--these keep changing for each total
DECLARE @Counter varchar(2)--this will increment from 2 to 40
SELECT @MyName ='tblG3>74Ex' +convert(varchar(3), @Extract)
SET @total1 =(SELECT COUNT(*)
FROM @MyName
WHERE (sSurgery_id ="S0" + @Counter) and (iExtract_nm = @Extract)
SELECT @MyName ='tblG335-74Ex' +convert(varchar(3), @Extract)
SET @total2 = (SELECT COUNT(*)
FROM @MyName
WHERE (sSurgery_id ="S0" + @Counter)and (iExtract_nm =@Extract)
insert into tblNew([35-74],[>74],etc,etc,Report4)
values (@total1,@total2,ect,ect,@report4)
it all works until I try to use the @MyName
Please put me out of my misery
Many thanks
David

View 1 Replies View Related

T-SQL (SS2K8) :: Proc Giving Error In One Session And Runs In Another

Nov 13, 2014

I have one drop and create procedure script in one sql session and execute the procedure in other session. Now when i am compiling the procedure in first session, it gets completed successfully.

Now when i move to other session and try to execute the procedure, it gives me error saying :

"Invalid column name 'ColumnName'."

Now when I execute the procedure in same session in which procedure was compiled, it runs successfully. Once run, I go back to my other session and it runs again.

View 9 Replies View Related

How To Get All Table Names From A Database?

Apr 13, 2007

I have two questions:



1. Which system table (data dictionary) I can select to get all table names in one database?

2. What sql command can I use to get a definition about a table?



Thanks

View 9 Replies View Related

Getting Table Names From AdventureWorks Database

Apr 24, 2008

Hello,
I have ran into a problem when i'm getting table names in c#.
I have tried the sql command:
select name from sysobjects where type='U' order by name
So it returns the names without a problem. But when I try to access to some tables using their names (to retrieve the columns) I sometimes get the error "Invalid object name" following by the name of the table.
So I realized the if the table was not under dbo user then i would get this error.
for example: "select name from ContactCreditCard"
 gives me error because in database management tool it is shown like this: Sales.ContactCreditCard
How can i fix this problem? How to get that prefix of the tables?
 
Thank you,
 

View 8 Replies View Related

How Can I Find All Table Names Defined In A Database?

Mar 10, 2001

I have a database and I want to retrieve informations about all tables
defined in this database. In other words I need the table list defined in
database. Can you help me?

Thank you.

View 1 Replies View Related

How To Get The List Of Table Names In A SQL2005 Database

Aug 31, 2005

How to get the list of table names in a SQL2005 database?

View 6 Replies View Related

List Table Names In A Database Having A Particular Column.

Aug 3, 2007

Can anybody tell me how to find out whether a particular column exists in any of the tables of a database and if it does, display the table names?


Thanks

View 3 Replies View Related

SQL 2005 Database Design (Table Names)

Apr 14, 2006

In the past, we had table names such as:
PurchaseOrders
SalesOrders

Now with SQL 2005, you can use schema namespaces, so it could become:
Purchasing.Orders
Sales.Orders

So essentially you can use exactly the SAME table names, in different schemas.

So... would you recommend to change to the last model, or just stay with the old way?
What is best practice?



One of the reasons why I ask this question is that I looked at the AdventureWorks sample database included with SQL Server 2005, and Microsoft is using:

Sales.SalesOrderDetail
Purchasing.PurchaseOrderDetail
etc...

Why not:
Sales.OrderDetail
Purchasing.OrderDetail
etc...

????????

View 1 Replies View Related

Create List Of Table Names And Size For A Database

May 5, 2004

Hi there,

I am trying to create a list of all the tables in one database and then list the size of each table. So for example I want to create a table with the table name and table size for one DB

E.g

Table1 1111KB
Table2 123300MB
Table3 120448KB

etc for all the tables in a particukar DB

I know there is a stored procedure to list the sizes: 'sp_spaceused' but not sure how to script all this together.

can anyone help please!!

From

NewToSQL

View 12 Replies View Related

Dynamically Pass Table Names And File Names To IS Package

Mar 1, 2015

I am designing a package to export staging tables into a flat file.The names of the tables will be: TableAStaging_YYYYMM and TableBStaging_YYYYMM. As you can see the names of the tables will be changing each month.

The flat files will have similar naming: C:MyPathFlatFileTableAStaging__YYYYMM and C:MyPathFlatFileTableAStaging__YYYYMM.I want to run the package as an sql job in two steps, one for each table.I need to dynamically pass the table names and file names (together with the path) to the IS package.

View 1 Replies View Related

Determine Table Names And Column Names At Runtime?

Jan 22, 2004

Hi

I was wondering if anyone has an idea of how we could find the table names and column names of the tables in our Sql server database at runtime/dynamically given our connection string? Please let me know.

Thanks.

View 5 Replies View Related

Column Names As Parameters

Aug 19, 2004

I would like to pass into a stored proc the column names I want it to return; how do I do this please?


So I pass in say:

@p_AccountNumber with a value of 'AccountNum'

and the SELECT that the sp fires is of the form

SELECT AccountNum from AccountTable

Any help appreciated

View 2 Replies View Related

SQL Server 2008 :: How To Delete Tables In Database Whose Table Names Match A Criteria

Jul 22, 2015

The database has approx. 2500 temporary tables. The temp tables match a pattern such as APTMP... I tried deleting the tables in SSMS with the statement, Delete from Information_Schema.tables where substring(table_name,1,5) = 'APTMP' This returns the error message"Ad hoc updates to system catalogs are not allowed".

What is the correct way to delete a group of tables whose name match a pattern from within SSMS?

View 9 Replies View Related

Best Way To Return Data From SQL Database, Without Giving Access To Database

May 8, 2008

Hello,

I have a quick question regarding getting data from a SQL database but I am slightly confused as to the best way to handle it.

Basically on of the projects I am working on I need to send data to another company, there are several calls required to the database to bring back various options for changing the questions asked on the front end.

Up to now all that has happened is there has been a mutual agreement between myself and this other company and they have just had access to the database to call a series of stored procs which I have written for them to access the data. Recently however the situation has changed and my client wants me stop them accessing the database however they still need to recieve the information from the database they recieve now.

What will be the best way to handle this? My knowledge of SQL is farily limited presently and I am only ust getting into learning a lot more about it.

Any help and advice would be greatly appreciated.

Kind regards,

Lee

View 5 Replies View Related

Database Keeps Giving Timeout Error

Apr 24, 2007

Hi All,

since the last upgrade SQL 2000 --> 2005, the biggest database I am working on (1.4 GB, with loads of binary data) keeps freezin at least one time per week. When I say 'freezin' I mean that you cannot query some of the tables as it gives a timeout error when trying.

I am not a DBA and I don't have any idea of what to do, the only thing which comes to my mind is that this database is too big, as if I go to the preperties window it says Space Available: 38 MB (what's that? there's really only 38 MB on this DB?).
I tried re-writing all mainteinment plans (full backup every night, log backup every hour), but I realized that the database keeps freezing (and the backup jobs keep running untill you stop them).

anyone could give any hint?

Thanks in advance,

Giovanni Idili

View 20 Replies View Related

Table Names And Field Names

Jan 21, 2004

I'm trying to do an update query that looks like this:

UPDATE

PAEMPLOYEE

SET PAEMPLOYEE.LOCAT_CODE = EMPLOYEE.PROCESS_LEVEL


FROM

PAEMPLOYEE A

JOIN EMPLOYEE B ON A.EMPLOYEE = B.EMPLOYEE

It's erroring out on the Employee prefix B.EMPLOYEE saying:

..."does not match with a table name or alias name used in the query"


Is it wrong or will it cause problems to have a field name the same as the table name?

View 5 Replies View Related

Optional Parameters In A Stored Proc?

May 19, 2004

Title speaks for itself really.
Is it possible to write a stored proc with optional parameters?
For example consider the following SELECT

SELECT FLD1, FLD2 FLD3 FROM TBL1

I'd like to add optional parameters to that statement so that if they wanted to narrow down the results by providing criteria for some fields they could - but didn't have to.

Is this possible?

View 4 Replies View Related

Stored Proc - Unknown Parameters

Jan 24, 2007

If a procedure is known but all parameters are not known, can I handle this using CommandBehavior.RetrieveParameters.
If yes, do I need to incur an extra round trip to server.

View 1 Replies View Related

Passing Parameters To Stored Proc

Oct 23, 2007



I have created a stored proc for a report, which works fine. I want to have the user enter a project ID to filter the report, so set the stored proc accordingly. However, I want the user to enter a 10 digit ID, which is the equivilent of two fields in the stored proc. My where statement is :

Where actv.ProjID + '-' + actv.Activity = @project

This works fine under the data tab, I can enter a full project and get the results I want. But I cannot preview the report without getting an error. I'm not sure how to add this to the report parameters, as it is two fields concatenated together. Any help would be appreciated!

View 3 Replies View Related

Giving Members Of A Team Copies Of A Database

Nov 25, 2007

I'm working in a team, and need to share a database between the group - we don't have the luxury of sharing a server and connecting to it.

So What we'd like to do is make a copy of the database schema, and then share that through our repository.

I figured I just need to copy the .mdf file from the sql server database folder, and put it in the visual studio directory to work on it?

So I've tried this, but when I try to create a TableAdapter to the database through visual studio, It gives me an "access denied". I figure this is probably something to do with security settings?

Do you think I'll need to change my Database connection from windows authentication to sql authentication?

I don't really know exactly how to do what I'm trying to do, so any help will be appreciated.

View 1 Replies View Related

Alter Table Datatype Giving Error Date To Bit

Nov 20, 2014

IF EXISTS (SELECT * FROM SYS.COLUMNS WHERE NAME =N'Case_Escalated__c' AND OBJECT_ID = OBJECT_ID(N'[Case]'))
begin
alter table [Case] alter column Case_Escalated__c bit null
print 'Case_Escalated__c altered sucessfully for [Case]'
end

Msg 1792, Level 16, State 1, Line 3
Alter table 'Case' failed because the added fixed column might cause existing data to go beyond the maximum allowable table row size of 8060 bytes.

View 4 Replies View Related

Stored Proc Update Optional Parameters

Dec 3, 2003

I have a stored procedure that updates about a dozen rows.

I have some overloaded functions that I should update different combinations of the rows - 1 function might update 3 rows, another 7 rows.

Do I have to write a stored procedure for each function or I can I handle it in the Stored Procedure. I realise I can have default values but I the default values could overwrite actual data if the values are not supplied but have been previously written.

Many thanks for any guidance.

Simon

View 5 Replies View Related

Getting Problem In Giving Database Permission To Group User

Jun 18, 2007

hi ,

I am getting some problem in using group in sql server login.

i have two NT groups in windows.i) developer and tester

I added a user Lalit in both gruop. I want to give db_owner permission on a particular database(Employee) to developer group and data_denyreader and deny_writer on same database(Employee) to tester group.



Now when i logging in to sql server using Lalit(windows authentication) iam not able to access the database(Employee).



Now my concern is that Lalit should have full access to the employee database when entered as developer user and limited access to employee database when entered as tester user.



how can i achieve this set up????



Please do help.

Thanks a lot in advance !!!!!!!!!!!!!!!!!!

View 1 Replies View Related

Giving Someone Read-only Access To A Database -- Beginner Question

Jun 29, 2007

Sorry for the simple question, but I'm not having any luck getting this to work: I need to give someone read-only access to everything in a database.



If someone could help me by giving me (or linking me to) a step-by-step, idiot-proof recipe for giving Bob in my office read-only access to the whole database, I'd be very grateful. And remember: I'm good at db programming, but completely ignorant on the subject of db admin.

View 3 Replies View Related

Data Driven Sub Calling Proc With Multiple Parameters

Aug 31, 2007

I have a couple of questions that I hope someone might be able to provide some direction on.



1. Why can't you call a proc when the proc uses temp tables? I wrote a simple proc (select * from table) and the data subscription works perfect. I then take that same query and put it into a temp table and the data set can't be validated by the subscription, Why?



2. Why can't you pass a simple execute statement in a data subscription? (execute dbo.RptTakeTheLeadFLSDinnerCompetition @FiscalQuarter ='2007-Q3', @StoreRegionID = '9231', @StoreType = 'Full-Line Store') works perfect in SQL but once you try and validate in the data subscription is fails.



3. Another question, why if I dumb down the proc and the number of parameters does it work? Are there limitations on the number of parameters you can pass into a proc from a data driven subscription?



Basically, I want to declare a few variables dynamically and pass them into a execute statement that calls the proc. Which in turn runs the report.



Any ideas on where I seem to be going wrong?


View 3 Replies View Related

Stored Proc Parameters Slowing Down Execution Majorly!

Jan 15, 2008

Hello:

Interestingly enough, I haven't come across this before. I have a SQL stored procedure which takes four parameters; periodstartdate (datetime), periodenddate (end time), hsgradyearstart (int), hsgradyearend (int)


[dbo].[CalculateActivityTotal]

-- Add the parameters for the stored procedure here

@periodstartdate datetime = '2007-01-01',

@periodenddate datetime = '2007-01-08',

@hsgradyearstart int = 1900,

@hsgradyearend int = 2007
AS...

If I run the stored procedure and pass the parameters using EXEC or

sp_executesql "CalculateActivityTotal '2008-01-04 12:00:00', '2008-01-11 12:00:00', 1900, 2008"

the stored proc takes well over ten minutes to run (it does a bunch of aggregation). If I modify the stored procedure to take no parameters, however, and I hardcode the dates in the stored proc using declare and set then it runs in 13 seconds. What could be causing my problem and how I can I go about resolving this? I need to pass the parameters via reporting server. Thanks!

View 2 Replies View Related

Calling CLR Stored Procedure From Within A CLR Table-valued Function Giving Errors

Apr 6, 2007

We are trying to create a TVF that executes a CLR Stored Procedure we wrote to use the results from the SP and transform them for the purposes of returning to the user as a table.






Code Snippet

[SqlFunction ( FillRowMethodName = "FillRow",

TableDefinition = "CustomerID nvarchar(MAX)",

SystemDataAccess = SystemDataAccessKind.Read,

DataAccess = DataAccessKind.Read,

IsDeterministic=false)]

public static IEnumerable GetWishlist () {

using (SqlConnection conn = new SqlConnection ( "Context Connection=true" )) {

List<string> myList = new List<string> ();

conn.Open ();

SqlCommand command = conn.CreateCommand ();

command.CommandText = "GetObject";

command.Parameters.AddWithValue ( "@map", "Item" );

command.CommandType = System.Data.CommandType.StoredProcedure;

using ( SqlDataReader reader = command.ExecuteReader ( System.Data.CommandBehavior.SingleRow )) {

if (reader.Read ()) {

myList.Add ( reader[0] as string );

}

}



return (IEnumerable)myList;

}

}



When command.ExecuteReader is called, I am getting an "Object not defined" error. However, the stored procedure can be used in SQL Management Studio just fine.






Code SnippetEXEC GetObject 'Item'



Is there some sorf of trick I am missing?



Thank you!

View 3 Replies View Related

Convert Dynamically Generated Parameters List Into Stored Proc

Mar 17, 2006

I have the following ASP code that builds part of the example SQL statement below (it's the same SQL as in my earlier thread here (http://www.dbforums.com/showthread.php?t=1214044) but a very different question):


if sFindTicketEventId > 0 then sSQL = sSQL & " AND [tblEvents].[id]=" & sFindTicketEventId
if sFindTicketStandId > 0 then sSQL = sSQL & " AND [tblStands].[id]=" & sFindTicketStandId


SELECT
[tblC].[id] AS CombinationID,
[tblC].[availability],
[tblC].[description],
[tblC].[price] AS combinationPrice,
[tblC].[combination_open],
[tblT].[TicketID] AS TicketID,
[tblT].[price] AS ticketPrice,
[tblT].[availability],
[tblT].[ticket_open],
[tblT].[quantity],
[tblT].[event_name],
[tblT].[event_open],
[tblT].[stand_name],
[tblT].[stand_open],
[tblT].[admission_start_date],
[tblT].[admission_end_date],
[tblT].[date_open],
[tblT].,
[tblT].,
[tblT2].[description],
[tblT2].[admin_description]
FROM(
SELECT
[tblCombinations].[id],
[tblTickets].[id] As TicketID, [tblTickets].[price], [tblTickets].[availability], [tblTickets].[ticket_open],
[tblCombinations_Tickets].[quantity],
[tblEvents].[event_name],
[tblEvents].[event_open],
[tblStands].[stand_name],
[tblStands].[stand_open],
[tblAdmissionDates].[admission_start_date],
[tblAdmissionDates].[admission_end_date],
[tblAdmissionDates].[date_open],
[tblBookingDates].[booking_start_date],
[tblBookingDates].[booking_end_date]
FROM [tblCombinations]
LEFT JOIN [tblCombinations_Tickets] ON [tblCombinations_Tickets].[combination_id] = [tblCombinations].[id]
LEFT JOIN [tblTickets] ON [tblCombinations_Tickets].[ticket_id] = [tblTickets].[id]
LEFT JOIN [tblEvents] ON [tblEvents].[id] = [tblTickets].[event_id]
LEFT JOIN [tblStands] ON [tblStands].[id] = [tblTickets].[stand_id]
LEFT JOIN [tblAdmissionDates] ON [tblAdmissionDates].[id] = [tblTickets].[admission_date_id]
LEFT JOIN [tblBookingDates] ON [tblBookingDates].[id] = [tblTickets].[booking_date_id]
LEFT JOIN [tblTicketConcessions] ON [tblTicketConcessions].[id] = [tblTickets].[ticket_concession_id]
LEFT JOIN [tblBookingQuantities] AS [tblBookingMinQuantities] ON [tblBookingMinQuantities].[id] = [tblTickets].[booking_min_quantity_id]
LEFT JOIN [tblBookingQuantities] AS [tblBookingMaxQuantities] ON [tblBookingMaxQuantities].[id] = [tblTickets].[booking_max_quantity_id]
LEFT JOIN [tblMemberships] ON [tblMemberships].[id] = [tblTickets].[membership_id]
WHERE 1=1
[B]AND [tblEvents].[id]=2
[B]AND [tblStands].[id]=3
--AND [tblAdmissionDates].[id]=@admissionDateId
--AND [tblBookingDates].[id]=@bookingDateId
--AND [tblTicketConcessions].[id]=@concessionId
--AND [tblBookingMinQuantities].[id]=@bookingMinQuantityId
--AND [tblBookingMaxQuantities].[id]=@bookingMaxQuantityId
--AND [tblMemberships].[id]=@membershipId
GROUP BY
[tblCombinations].[id],
[tblTickets].[id],
[tblTickets].[price], [tblTickets].[availability], [tblTickets].[ticket_open],
[tblCombinations_Tickets].[quantity],
[tblEvents].[event_name],
[tblEvents].[event_open],
[tblStands].[stand_name],
[tblStands].[stand_open],
[tblAdmissionDates].[admission_start_date],
[tblAdmissionDates].[admission_end_date],
[tblAdmissionDates].[date_open],
[tblBookingDates].[booking_start_date],
[tblBookingDates].[booking_end_date]
) as [tblT]
JOIN [tblCombinations] as [tblC] on [tblT].[id]=[tblC].[id]
LEFT JOIN [tblTickets] as [tblT2] on [tblT].[TicketID]=[tblT2].[id]


I want to turn this SQL into a stored proc; there are currently about 8 parameters that I want to pass into it. The field value for each will be either NULL or a positive integer, and the paramater will be passed in as an integer.

If the passed parameter value is a positive integer then it should return all records where the corresponding field value matches that integer. If the passed parameter is 0, it should return all rows regardless of whether the field value is an integer or NULL.

And I can't for the life of me figure out how to do it. Do I need an IF statement in there or something?

:confused:

View 2 Replies View Related

Passing A Comma Delimited String Of Parameters To A Stored Proc

Jul 30, 2007

Hello,
I have a number of multi-select parameters which I would like to send to a stored procedure within the dataset for use in the stored procedure's IN() statement which in turn is used to filter on or out particular rowsets.

I considered using a hidden string parameter set = " ' " + join(parameter.value, ',') + " ' " so that the hidden parameter would then contain a comma delimiated string of the values selected, which would then be sent on to the stored proc and used in the WHERE clause of one of the queries internal to the stored proc.
But before I start dedicating time to do this I wanted to inquire if anyone here with far more expertise could think of a faster or less system heavy method of creating a single string of comma delimited parameter selections?

Thanks.

View 3 Replies View Related

Maintenance Plan - Back Up Database Task Fails Without Giving A Real Clue On How To Fix It.

Apr 18, 2008

Created a maintenance plan to backup my sharepoint databases.
When I execute it the following error occurs:
Execution failed. See the maintenance plan and SQL Server Agent job history logs for details:
Additional Information:
Job 'SharePointBackUp.Backup_SharePoint faild. (SqlManagerUI)
- Execute maintenance plan. SharePointBackUP (Error)
Messages
* Execution failed. See the maintenance plan and SQL Server Agent job history logs for details.

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

Job 'SharePointBackUP.Backup_SharePoint' failed. (SqlManagerUI)


When checking the Maintenance PlansharePointBackUP log it is empty!
Under Job History I thinks this:
Date 4/18/2008 12:55:35 PM
Log Job History (SharePointBackUP.Backup_SharePoint)
Step ID 1
Server DESD7
Job Name SharePointBackUP.Backup_SharePoint
Step Name Backup_SharePoint
Duration 00:00:00
Sql Severity 0
Sql Message ID 0
Operator Emailed
Operator Net sent
Operator Paged
Retries Attempted 0
Message
Unable to start execution of step 1 (reason: line(1): Syntax error). The step failed.
line 1? Is that line one of the T-SQL statement? Because if that's the case then it's not because I copied and pasted the line in to a query and it executed without error.
Under SQL Agent there are no entries!
So what bloody log am I suppose to be checking?! This is very frustrating.
I then copied and pasted every sql statement in to a query and THEY all ran just fine.

What's going wrong here, and how can I correct it?

View 5 Replies View Related

SSIS Loading DWH Staging Area When Table Names Is Selected From Table List

Aug 31, 2007

Hello,
Maybe anyone have done that before?
I have table where i store SOURCE_TABLE_NAME and DESTINATION_TABLE_NAME, there is about 120+ tables.
i need make SSIS package which selects SOURCE_TABLE_NAME from source ole db, and loads it to DESTINATION_TABLE_NAME in destination ole db.

I made such SSIS package. set ole db source data access mode to table or view name variable.
set ole db destination data access mode to table or view name variable. set to variables defoult values (names of existing tables)
but when i loop table names is changed, it reports error, that can map columns, becouse in new tables is different columns.

how to solve that problem?

View 5 Replies View Related







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