Passing Table Names As An Argument In A Procedure

May 7, 2008

hai <br>

<p>i have a procedure where in which i want to access a specific table whose name will be passed into procedure as argument. Here is the peice of code i have made.</p>

CREATE PROCEDURE outputtable @tablename nchar(10) AS<br>

begin<br>

.........................<br>

insert into @tablename (classno) values (@cno)<br>

.................................<br>

END<br>

 

<p> I get the following error message :</p>

Msg 1087, Level 15, State 2, Procedure................<br>

Must declare the table variable "@tablename".<br>

 <p>

Is there anyway i can get around this one.   I will be grateful if anyone can help me</p>

View 5 Replies


ADVERTISEMENT

Passing Variable Table Names To Stored Procedure

May 5, 2000

I need to execute a stored procedure which selects all columns from the passed table. The table used is a variable.

Select * from @Passedtablename. This won't work. Any insights.

View 1 Replies View Related

Passing Table Names To Table Valued Functions

May 25, 2008

Hello,
It is possible to write stored procedures which take table names as parameters; is it also possible to do this with table valued functions?

For example, a simple stored procedure is this:

CREATE PROCEDURE SelectTop(@tableName sysname)
AS
BEGIN

Execute('Select top 10 * from ' + @tableName + ';')

END

I want to be able to do the analogous thing with a table valued function (so that I can query the result set, without having to create a temp table). How should I do this (i.e., pass a tablename as an argument to a table valued function)?

View 11 Replies View Related

Argument Data Type Varchar Is Invalid For Argument 3 Of Convert Function

Jan 25, 2013

Where did i do wrong in conversion

original query
dateadd(hour, datediff(hour,CONVERT(VARCHAR(19),B.CreateDate,111 ),B.CreateDate)

I tried to use convert(varchar(50),Datediff,21)

Below is the exact code..

convert(varchar(50),dateadd(hour, datediff(hour,CONVERT(VARCHAR(19),B.CreateDate,111 ),B.CreateDate),21)

View 10 Replies View Related

Argument Data Type Text Is Invalid For Argument 1 Of Replace Function.

May 14, 2008



Hi There,

Could someone please tell me why I am getting the above error on this code:

select (replace
(replace
(replace
(replace (serviceType, 'null', ' ')
, '<values><value>', ' ')
, '</value><value>', ',')
, '</value></values>', ' '))
from credit


serviceType (text,null)

Thanks,
Rhonda

View 1 Replies View Related

Dynamic Table Names In Stored Procedure...

Jul 2, 2007

Hello all,

Im just wondering... is there any way to have dynamic table names, so that, say for instance, i have 4 stored procedures, that all do the same thing, just to four different tables. is there any way to have 1 stored procedure, and pass through the table name???

Adding the four statements into one statement is not an option, as i only need to execute one at a time..., not all four at once...

Cheers,
Justin

View 4 Replies View Related

Stored Procedure Table Names To View

Sep 7, 2005

I need help to create a stored procedure to get the table names from a database and create a Union view. There are over 100 tables.

View 3 Replies View Related

How To Pass Table Names To A Stored Procedure

Dec 16, 2005

Hi all,Seems like a fundamental question to me but I dont have a definiteanswer for it, Gurus please enlighten me.I have a table 'Table1' whose structure changes dynamically based onsome configuration values from another table. This table is being usedby a program, It was initially used by this program which ran as asingle task (executing at only a specific interval) but now the programhas to be run mutiple times some coinciding with each othe - whichmeant that table structure will change as 2 programs are runningsimultaneously... and therefore I have decided to use seperate tablenames that each has a structure of its now.I use this table name 'Table1' in about 10-15 stored procedures andUDF'sto make the long story short: Since I will not know which table I willbe using in the program I want to pass the table name as an argument tothe SP and UDF's and then access this param in the'select's/updates/inserts' - but this doesn't work unless I use DynamicSQL.Is there any other way of passing table names as parameters and thenusing then in the procs?any ideas will be really helpful.adi

View 5 Replies View Related

Variables As Table Or Column Names In A Stored Procedure

Apr 16, 2008

I would like to use variables to set the table name and some column names of a SQL Query in a stored procedure (the variable values will come from a webpage)... something like this:ALTER PROCEDURE dbo.usp_SelectWorkHours
@DayName varchar,@DayIDName varchar
AS
BEGINSELECT @DayName.InTime1, @DayName.OutTime1, @DayName.InTime2, @DayName.OutTime2 FROM @DayName
INNER JOINWorkHours ON @DayName.@DayIDName = @DayName.@DayIDName
INNER JOINEmployees ON WorkHours.WorkHoursID = Employees.WorkHoursID
END
RETURN
...is this possible?? if so how?
Thanks

View 2 Replies View Related

Passing Table Name To Stored Procedure Dynamicaly

Dec 27, 2007

 It's my code: 1 CREATE PROCEDURE SearchFunction2 @SQ nvarchar(30),3 @pType nvarchar(11),4 @pCol nvarchar(11)5 AS6 BEGIN7 SELECT * FROM [data] 8 WHERE ([type] LIKE '%'+@pType+'%') AND (@pCol LIKE '%'+@SQ+'%')9 END
10 GOWhen I replace '@pCol' with 'nameCol' it works fine, but when i pass it trough parameter in my aspx page [pCol.Value='nameCol'] it does not work!  

View 2 Replies View Related

Passing A Dynamic Table Name To A Stored Procedure

May 19, 2004

Is this possible?

I know this doesn't work but I'll post it anyways so you can see what I'm trying to accomplish.



CREATE PROCEDURE GetStuff
@something int,
@tablename varchar(50)
AS
SELECT * FROM @tablename WHERE something = @something



Like I say, I know it doesn't work...but does anyone know how to accomplish something like this?

View 1 Replies View Related

Passing Table Name In Stored Procedure Got Error

May 13, 2008

ALTER PROCEDURE [dbo].[sp_STATEWLEVEL_DAILY]
@STATE varchar(50),@TBLNAME varchar(50)

AS
BEGIN TRANSACTION -- Start the transaction
TRUNCATE TABLE @TBLNAME;
SELECT
t1.Date_Taken as 'DATE', t1.Time as 'TIME',
t1.Main_ID as 'MAIN_ID', t1.WATER_ULEVEL as 'WATER_ULEVEL'
FROM dbo.SEL t1 INNER JOIN dbo.station_info t2
ON t1.Main_ID=t2.Main_ID
WHERE t2.STATE=@STATE
AND t1.Date_Taken=CONVERT(VARCHAR(10), GETDATE(), 101)
ORDER BY t1.Date_Taken, t1.Time

-- See if there is an error
IF @@ERROR <> 0
-- There's an error b/c @ERROR is not 0, rollback
ROLLBACK
ELSE
COMMIT -- Success! Commit the transaction

Error said Incorrect syntax near '@TBLNAME'.

View 8 Replies View Related

Passing A Table As An Input To Stored Procedure

Jun 18, 2008

Hi everyone,

Is that possible to passing a table as an input to Stored Procedure?

Thanks in advance

View 1 Replies View Related

STORED PROCEDURE - Passing Table Name As A Parameter

Nov 29, 2005

I am trying to develop a stored procedure for an existing application thathas data stored in numerous tables, each with the same set of columns. Themain columns are Time and Value. There are literally hundreds of thesetables that are storing values at one minute intervals. I need to calculatethe value at the end of the current hour for any table. I am a little newto SQL Server, but I have some experience with other RDBMS.I get an error from SQL Server, complaining about needing to declare@TableName in the body of the procedure. Is there a better way to referencea table?SteveHere is the SQL for creating the procedure:IF EXISTS(SELECTROUTINE_NAMEFROMINFORMATION_SCHEMA.ROUTINESWHEREROUTINE_TYPE='PROCEDURE'ANDROUTINE_NAME='udp_End_of_Hour_Estimate')DROP PROCEDURE udp_End_of_Hour_EstimateGOCREATE PROCEDURE udp_End_of_Hour_Estimate@TableName VarCharASDECLARE @CurrentTime DateTimeSET @CurrentTime = GetDate()SELECT(SELECTSum(Value)* DatePart(mi,@CurrentTime)/60 AS EmissonsFROM@TableNameWHERETime BETWEENDateAdd(mi,-DatePart(mi,@CurrentTime),@CurrentTime)AND@CurrentTime)+(SELECTAvg(Value)* (60-DatePart(mi,@CurrentTime))/60 AS EmissionsFROM@TableNameWHERETime BETWEENDateAdd(mi,-10,@CurrentTime)AND@CurrentTime)

View 15 Replies View Related

Procedure Or Function Has Too Many Argument Specified.

May 27, 2008

 Hey, friends, i have a problem on my bank transaction page now: Procedure or function has too many argument specified.people can log in by their usernames, 1 username can have many accounts, there are 2 account types:'c', 's'. after people login, they are only allowed to withdraw money from their own account: here is some of my codes:  1 else if (DropDownList3.SelectedItem.Text == "withdraw")2 {3 SqlConnection sqlCon = new SqlConnection("Data Source=bandicoot.cs.rmit.edu.au;Initial Catalog=shuli;User ID=test;Password=test");4 SqlCommand cmd = new SqlCommand("usp_withdraw", sqlCon);5 string spResult = "";6 cmd.CommandType = CommandType.StoredProcedure;7 cmd.Parameters.Add("@username", SqlDbType.NVarChar).Value = Session["username"].ToString();8 cmd.Parameters.Add("@AccountFrom", SqlDbType.VarChar).Value = TextBox3.Text;9 cmd.Parameters.Add("@Amount", SqlDbType.Decimal).Value = TextBox5.Text;10 cmd.CommandType = CommandType.StoredProcedure;11 sqlCon.Open();12 spResult = cmd.ExecuteScalar().ToString();13 if (string.Compare(spResult, "Execute successfully") == 0)14 {15 SqlDataSource with = new SqlDataSource();16 with.ConnectionString = ConfigurationManager.ConnectionStrings["shuliConnectionString"].ToString();17 18 with.InsertCommand = "insert into Transactions(TransactionType,AccountNumber,DestAccount,Amount,Comment,ModifyDate) values ('W','" + TextBox3.Text + "','" + TextBox3.Text + "','" + TextBox5.Text + "','" + TextBox2.Text + "','" + DateTime.Now.ToLocalTime() + "')";19 int inertRowNum = with.Insert();20 Server.Transfer("~/deposit_withdraw_confirm.aspx");21 }22 else23 {24 Server.Transfer("~/deposit_withdraw_error.aspx");25 }26
  here is my store procedure set ANSI_NULLS ONset QUOTED_IDENTIFIER ONgo-- =============================================-- Author:        <Author,,Name>-- Create date: <Create Date,,>-- Description:    <Description,,>-- =============================================ALTER Procedure [dbo].[usp_withdraw](    @AccountFrom Varchar(20),    @Amount Decimal(10,2))AsDECLARE @ReturnMsg AS VARCHAR(20)DECLARE @balance AS Decimal(10,2)DECLARE @username AS nvarchar(50)SELECT @balance = balanceFROM Account,LoginWHERE   Account.CustomerID=Login.CustomerID AND Login.UserID= @username and AccountNumber = @AccountFromIF (    SELECT AccountType     FROM Account, Login    Where  Account.CustomerID=Login.CustomerID AND Login.UserID= @username and AccountNumber = @AccountFrom    ) ='c'BEGIN     BEGIN TRAN        IF (@balance - @Amount) > 199                                    BEGIN            UPDATE Account            SET balance= balance-@Amount            WHERE AccountNumber=@AccountFrom                  And (balance - @Amount) > 199                                            SET @ReturnMsg = 'Execute successfully'            COMMIT TRAN        END        ELSE        BEGIN            SET @ReturnMsg = 'Execute with error'            ROLLBACK TRAN                  END    SELECT @ReturnMsg     ENDIF (    SELECT AccountType     FROM Account    Where AccountNumber = @AccountFrom    ) ='s'BEGIN     BEGIN TRAN        IF (@balance - @Amount) > 0                                    BEGIN            UPDATE Account            SET balance= balance-@Amount            WHERE AccountNumber=@AccountFrom                  And (balance - @Amount) > 0                                            SET @ReturnMsg = 'Execute successfully'            COMMIT TRAN        END        ELSE        BEGIN            SET @ReturnMsg = 'Execute with error'            ROLLBACK TRAN                  END    SELECT @ReturnMsg     ENDI think the problem is in Line 7cmd.Parameters.Add("@username", SqlDbType.VarChar).Value = Session["username"].ToString();this is to get the current login user's uername.  

View 4 Replies View Related

Passing Table Name And Order By Parameter To Stored Procedure

Jul 27, 2007

can i pass the name of the table and the "order by" column name to stored procedure?
 i tried the simple way
(@tablename varchar and then "select * from @tablename)
but i get error massesges. the same for order by...
what is the right syntex for this task?

View 2 Replies View Related

[|-)] Error: Stored Procedure Has Too Many Argument....

Feb 11, 2008

Hello frend...i have a problem with my application when i'm trying to delete a certain data from gridview...i have a store procedure that already create in my mssql server...and in datasource i'm using command that i've already created in my mssql server...the problem is i dont know how i can send my value to the parameter in datasource.....and one more thing what is exaclty the error with 'Store procedure has <my function> too many argument" occur? Please help me....so i paste my code below to easier and detect my problem....(sorry my english are no good)....
1) This is my code in asp.net
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:SqlDataSource ID="SqlDSRole" runat="server" ConnectionString="<%$ ConnectionStrings:PVMCCon %>"
DeleteCommand="Roles_delete"
DeleteCommandType="StoredProcedure"
SelectCommand="Roles_view"
SelectCommandType="StoredProcedure">
<DeleteParameters>
<asp:Parameter Name="roleName" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Role_application_id"
DataSourceID="SqlDSRole" ForeColor="#333333" GridLines="None" PageSize="4">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:TemplateField HeaderText="Role Application Id" Visible="False">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Role_application_id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="roleApplicationIdLabel" runat="server" Text='<%# Eval("Role_application_id") %>'></asp:Label>
</EditItemTemplate>
<AlternatingItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Role_application_id") %>'></asp:Label>
</AlternatingItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role Name" >
<ItemTemplate>
<asp:Label ID="roleName" runat="server" Text='<%# Eval("Role_name") %>' CssClass="LabelInfo" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="roleNameTxt" runat="server" Text='<%# Bind("Role_name") %>' Width="200px"></asp:TextBox>
</EditItemTemplate>
<AlternatingItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("Role_name") %>' CssClass="LabelInfo"></asp:Label>
</AlternatingItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role Description">
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Eval("Role_description") %>' CssClass="LabelInfo"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="roleDescriptionTxt" runat="server" Height="30px" Text='<%# Bind("Role_description") %>'
TextMode="MultiLine" Width="300px"></asp:TextBox>
</EditItemTemplate>
<AlternatingItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# Eval("Role_description") %>' CssClass="LabelInfo"></asp:Label>
</AlternatingItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#E0E0E0" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
2) And this is my Store procedure that i created in mssql server
Store Procedure: Roles_view
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[Roles_view]
AS
BEGIN
SET NOCOUNT ON;
SELECT *
FROM Role
END
Store Procedure: Roles_delete
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[Roles_delete]
@roleName varchar(50)
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM Role
WHERE Role_name LIKE @roleName
END
 3) The problem is when i'm trying to delete my certain data, the message box appear and say "Procedure or function Roles_delete has too many argument specified".what should i do????anabosy please help me..

View 5 Replies View Related

WHERE Clause' Search Condition From Argument In A Stored Procedure.

Nov 7, 2007

Hello

I wonder if someone could suggest a way to obtain the following. Using SQL Server 2005 I want to create some stored procedures. I want to query the DB with various filter arguments and combinations of these. One way would be to create one stored procedure for each function signature. However, as the number of combinations of filter is large, if possible I'd rather have a generic input to the each stored procedure that corresponds to the entire WHERE clause' search condition.

The stereotype behavior I'm looking for is:

SELECT myField
FROM myTable
WHERE @mySearchCondition

Does any one have some good suggestion, code samples and/or links?

Kind regards
Jens Ivar

View 2 Replies View Related

T-SQL (SS2K8) :: Passing Multiple Parameters With Table Valued Parameter To Stored Procedure?

May 21, 2014

Can we Pass table valued parameters and normal params like integer,varchar etc..to a single stored procedure?

View 1 Replies View Related

SQL Server 2012 :: Stored Procedure Argument For Select Where Value IN Statement

Feb 17, 2014

I have a stored procedure that ends with

Select columnname from tablename order by ordercolumn

We will call that "sp_foldersOfFile". It takes 1 parameter, a fileID (int) value.

The result when I execute this from within Management Studio is a single column of 1 to n rows. I want to use these values in another stored procedure like this:

Select @userCount = COUNT(*) from permissions where UserID = @userID and
(projectid = @projectID or projectid=0) and
clientid = @clientID and
folderpermissions in (dbo.sp_FoldersOfFile(@fileID))

The Stored Procedure compiles but it does not query the folderpermissions in the selected values from the sp_FoldersOfFile procedure. I'm sure it is a syntax issue.

View 9 Replies View Related

Passing Variables And Column Names To EXEC

Oct 9, 2007

Hello, I'm quite new to T-SQL, but since I'm trying to create a statistics page on database contents (Counting savesets in Enterprise Vault saveset Databases) I prefer to do the coding in the databases.
I create temp tables for the distinct partitions in the saveset table. Then I pass 2 variables to the EXEC function, but it seems unable to pass the ['+@idpartition+']-variable as a value:
Declare @EVBase varchar(20)Declare @IdPartition INTSet @EVBase=(SELECT EVMbxName from Servers) Set @IdPartition=(SELECT TOP 1 Dist_Partitions FROM TEMP_EV1)EXEC('SELECT COUNT (IdPartition)FROM ['+@evbase+']..SAVESET SS LEFT OUTER JOIN SavesetStore SSS ON SS.SavesetIdentity = SSS.SavesetIdentityWHERE [IdPartition] =  ['+@idpartition+'] AND StoreIdentifier IS NULL')
Server: Msg 207, Level 16, State 3, Line 2Invalid column name '0'.
If I change the last line to: WHERE [IdPartition] =  2 AND StoreIdentifier IS NULL')The script runs fine - but I need the value from the table. Any help will be appreciated.
Best regards, Tim 
 
 

View 4 Replies View Related

Passing Object Names To Stored Procedures

May 31, 2001

Can anyone tell me the correct syntax for passing a Table Name to a Stored Procedure that uses the Table Name to do an INSERT into that Table ?

Below is my poor effort at the SQL.

Thanks.

CREATE PROCEDURE InsertOrderLine

@OrderNo INT,
@ProductID VARCHAR(15),
@UnitCost MONEY = 0,
@Quantity FLOAT = 0,
@Discount MONEY = 0,
@Tax MONEY = 0,
@TABLENAME VARCHAR(200)

AS

DECLARE @SQL VARCHAR(1000)

SELECT @SQL='INSERT ' + @TABLENAME + ' (OrderNo,
ProductID, UnitCost, Quantity, Discount, Tax) VALUES
(@OrderNo + ',' + @ProductID + ',' + @UnitCost + ',' + @Quantity +
',' + @Discount + ',' + @Tax)'

GO

View 1 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

The Age Old Argument Of Temp Table Vs Table Variable

Jan 26, 2007

Hi All,Hope someone can help me...Im trying to highlight the advantages of using table variables asapposed to temp tables within single scope.My manager seems to believe that table variables are not advantageousbecause they reside in memory.He also seems to believe that temp tables do not use memory...Does anyone know how SQL server could read data from a temp tablewithout passing the data contained therein through memory???Is this a valid advantage/disadvantage of table variables VS temptables?

View 2 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

Table Type Argument As OUTPUT In PROC

Jun 1, 2013

how can i define table type argument as OUTPUT in PROC and don't READONLY? if it's not possible, is there another way to do same this?

View 1 Replies View Related

Sending Table Variable Argument Using MSFT JDBC Driver

Nov 21, 2006



I want to call a stored procedure that has a table variable as its parameter. I am using the MSFT SQL Server 2005 JDBC driver 1.1, however I don't know how to construct a table variable from the Java side to place within a CallableStatement. The CallableStatement interface allows me to set various types of parameters (e.g. Boolean, Byte, Blob, Array, etc.) but I don't see anything for table variable.

Is there a way to do this?

View 3 Replies View Related

Sending Table Variable Argument Using MSFT JDBC Driver

Nov 20, 2006

Hi. I want to call a stored procedure that has a table variable as its parameter. I am using the MSFT SQL Server 2005 JDBC driver 1.1, however I don't know how to construct a table variable from the Java side to place within a CallableStatement. The CallableStatement interface allows me to set various types of parameters (e.g. Boolean, Byte, Blob, Array, etc.) but I don't see anything for table variable.

Is there a way to do this?

View 7 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

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

Table Names In Stored Procedures As String Variables And Temporary Table Question

Apr 10, 2008

How do I use table names stored in variables in stored procedures?




Code Snippetif (select count(*) from @tablename) = 0 or (select count(*) from @tablename) = 1000000





I receive the error 'must declare table variable '@tablename''

I've looked into table variables and they are not what I would require to accomplish what is needed.
After browsing through the forums I believe I need to use dynamic sql particuarly involving sp_executesql. However, I am pretty new at sql and do not really understand how to use this and receive an output parameter from it(msdn kind of confuses me too). I am tryin got receive an integer count of the records from a certain table which can change to anything depending on what the user requires.




Code Snippet

if exists(Select * from sysobjects where name = @temptablename)
drop table @temptablename




It does not like the 'drop table @temptablename' part here. This probably wouldn't be an issue if I could get temporary tables to work, however when I use temporary tables i get invalid object '#temptable'.

Heres what the stored procedure does.
I duplicate a table that is going to be modified by using 'select into temptable'
I add the records required using 'Insert into temptable(Columns) Select(Columns)f rom TableA'
then I truncate the original table that is being modified and insert the temporary table into the original.

Heres the actual SQL query that produces the temporary table error.




Code Snippet
Select * into #temptableabcd from TableA

Insert into #temptableabcd(ColumnA, ColumnB,Field_01, Field_02)
SELECT ColumnA, ColumnB, Sum(ABC_01) as 'Field_01', Sum(ABC_02) as 'Field_02',
FROM TableB
where ColumnB = 003860
Group By ColumnA, ColumnB

TRUNCATE TABLE TableA

Insert into TableA(ColumnA, ColumnB,Field_01, Field_02)
Select ColumnA, ColumnB, Sum(Field_01) as 'Field_01', Sum('Field_02) as 'Field_02',
From #temptableabcd
Group by ColumnA, ColumnB




The above coding produces

Msg 208, Level 16, State 0, Line 1

Invalid object name '#temptableabcd'.

Why does this seem to work when I use an actual table? With an actual table the SQL runs smoothly, however that creates the table names as a variable problem from above. Is there certain limitation with temporary tables in stored procedures? How would I get the temporary table to work in this case if possible?

Thanks for the help.


View 6 Replies View Related

SQL Server 2012 :: Return A Table Of Table-names Dynamically?

Sep 14, 2015

I have a function that returns a table from a comma-delimited string.

I want to take this a step further and create a function that will return a set of tablenames in a table based on a 'group' parameter which is a simple integer...1->9, etc.Obviously, what I am doing is not working out.

CREATE FUNCTION dbo.fnReturnTablesForGroup
(
@whichgroup int
)
RETURNS @RETTAB TABLE (
TABLENAME VARCHAR(50)

[code]....

View 9 Replies View Related

Passing Dates To A Procedure

Mar 6, 2006

im throwing up some errors

Syntax error converting datetime from character string.

im sending 2 asp:Text fields to the procedure

in the format dd/mm/yyyy

i.e. 06/03/2006

the table im inserting it into is set to datetime

within the procedure i have tried both
@Date1 DateTime,
@Date2 DateTime

@Date1 Nvarchar(50),
@Date2 Nvarchar(50)

and it still throws up Syntax error converting datetime from character string.

now im not sure if i should pass it to the Procedure as Nvarchar then Convert it within the procedure ..

or change the table type to nvarchar and just insert into a non date format table type.

View 11 Replies View Related







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