Dynamic SQL In Retrun Table Procedures
May 22, 2007
I'm having problems with dynamic sql within a funtion that returns a table. Here's an example, it compiles but on running gives me an error allong the lines that calling sub procedures is not permitted. I'm assuming the problem is inserting into teh return table, can it be done? should I declare @MyTable as a parameter using the sp_executesql call? or have I completely missed something?
Regards,
Andrew
Example routine, not that far from what my actual code looks like.
CREATE FUNCTION GetMyRecords
(
@date DateTime
)
RETURNS
@MyTable TABLE
(
RECORDID BigInt
)
AS
BEGIN
DECLARE @SQL Varchar(1000)
DECLARE @dayOfWeek int
DECLARE @fld varchar(10)
SET @dayOfWeek = DatePart( dw, @date )
if( @dayOfWeek = 1 )
@fld = "SUNDAY"
if( @dayOfWeek = 2 )
@fld = "MONDAY"
etc...
Set @SQL = N'Insert into @MyTable Select MyTestTable.ID from MyTestTable Where MyTestTable.' + @fld + ' > 0 '
Exec( @SQL )
RETURN
END
GO
View 4 Replies
ADVERTISEMENT
Sep 16, 2004
Hello -
I dont know something weired happened on our MSSQL server today. We are able to connect to any Databases from Enterprise Manager from a Remote server.
Once we logged in and connected to a database on my database server, it keep prompting for the user id and password as we browsing through different tables in that database?
(Right click on the table then select Open Table -> Return all rows -> and it prompts for password )
Now when we enter password the contents of Table are displayed and now when we try to see contents of another table in the database it again prompts for password.
Any Idea whats wrong? How this can be resolved as it was not happening before .. :(
View 1 Replies
View Related
May 31, 2007
hi all i have question about this procedure
when i write this the data return this is nice okUSE [DigitalFirm]
GO
/****** Object: StoredProcedure [dbo].[SearchTaskName] Script Date: 05/31/2007 21:44:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[SearchTaskName]
(@TaskName varchar(50)
)
as
select a.TaskId,a.TaskName,p.fullName,a.Sdate,a.Fdate
from Assign_Task a,Task_Emp te,Personal p,Employee ewhere te.TaskId=a.TaskId and te.IDNO=e.IDNO and p.SSN=e.IDNO and a.TaskName =@TaskName
and when i write this procedure in Sql server 2005
the i can show data and it is right and work
then when i want to exam this procedur in my web no have any data
please tell me why??
USE [DigitalFirm]
GO
/****** Object: StoredProcedure [dbo].[SearchTaskName] Script Date: 05/31/2007 21:44:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[SearchTaskName]
(@TaskName varchar(50)
)
as
select a.TaskId,a.TaskName,p.fullName,a.Sdate,a.Fdate
from Assign_Task a,Task_Emp te,Personal p,Employee e
where te.TaskId=a.TaskId and te.IDNO=e.IDNO and p.SSN=e.IDNO and a.TaskName like '@TaskName%'
thanx
View 6 Replies
View Related
Mar 18, 2004
REF: http://msdn.microsoft.com/netframework/default.aspx?pull=/library/en-us/dndotnet/html/storedprocsnetdev2.asp
It seems dynamic SQL is just as efficient as stored procedures in terms SQL Server caching. Any comments?
View 3 Replies
View Related
Jun 9, 1999
I open a recordset using a string to call a stored procedure. In the stored
procedure I create a temporary table and use the exec function to fill the
table. I then select * the table and drop the temporary table. The problem
is the recordset will not even open. My script keeps getting a "The
operation requested by the application is not allowed if the object is
closed. " error when points to the line after rs.Open is called. This line
checks for rs.EOF. When I Response.Write the SQL statement and paste this
into an ISQL session I get the output I am looking for. The only difference
is above the records I get a "# row(s) affected" which maybe from the
Insert. Does anyone know what is wrong here?
David Stanek
View 1 Replies
View Related
Jun 12, 2006
Hello, I'm trying to create a Stored Procedure who receives the table name as a parameter, then uses a cursor to obtain every column name and then builds a string like SELECT col1, col2, ... from TABLE
In fact that would be the same as SELECT * FROM table; but I can't do this, because I'll be using this stored procedure to loop through many tables that has different quantity of columns with a DTS, and if a specify the *, then the DTS wouldn't let me do the select with tables with different quantity of fields.
Could you help me please, because my code isn't working:
CREATE PROCEDURE dbo.stp_Test
(
@tablename AS VARCHAR(50)
)
AS
DECLARE @columnname varchar(50)
DECLARE @strsql Nvarchar(500)
DECLARE @query varchar(4000)
SET NOCOUNT ON
DECLARE c1 CURSOR FOR
SELECT column_name FROM information_schema.columns
WHERE table_name = @tablename
OPEN c1
FETCH NEXT FROM c1 INTO @columnname
WHILE @@fetch_status = 0
BEGIN
IF (@strsql is null)
BEGIN
SET @strsql=@columnname
END
ELSE
BEGIN
SET @strsql = @strsql + ',' + @columnname
END
FETCH NEXT FROM c1 INTO @columnname
END
CLOSE c1
DEALLOCATE c1
SELECT @query = 'SELECT ' + @strsql + ' FROM ' + @tablename
EXEC @query
SET NOCOUNT OFF
GO
View 4 Replies
View Related
Aug 1, 2006
Okay, I have sort of a peculiar permissions question I am wondering if someone can help me with. I'm suspect there's a simple answer, but I'm unaware of it. Basically, here's the scenario...
I have a CLR stored procedure which does some dynamic SQL building based on values sent in via XML. It's a CLR stored procedure using XML because I want to build a parameterized statement (to guard against SQL Injection) based on a flexible number of parameters which are basically passed in the XML.
The dynamic SQL ends up reading from a table I'll call TableX and I actually discovered an (understandable) quirk with security.
Basically, the connection context is impersonating a low-privilaged Windows account ("UserX") coming from a .NET application. UserX has no permission to the table referenced in the dynamic SQL and because of the dyanmic nature of the query, the stored procedure apparently adopts the security context of UserX. Naturally, this throws a security exception saying UserX has no SELECT permission on TableX.
Now, I can give UserX read permission to the table in question to get things running, but one of the points of using stored procedures is to defer security to the procedure level vs. configuration for tables or columns.
So in striving toward my ideal of security at the procedure level, my question is what is the best way to allow minimum privilege in this case?
I thought about having the internals of the CLR stored procedure run under a different (low-privalaged) security context, but I am wondering if there's an alternate configuration that may use the same connection, and be as secure, but simpler.
View 8 Replies
View Related
Oct 7, 2006
Hi there,
I would like to know how to create Dynamic stored procedure which defines TableName as a Variable and return all fields from this Table.
And also how to Dynamicly create a sp_GetNameByID (for instance)
using vars only.
Thanks
It would be very helpfull to me if you could give links of Dynamic SQL tutorials from which i can learn.
View 1 Replies
View Related
Feb 13, 2008
Hi!
I have an integration code write in T-SQL. It´s a TRIGGER that when some data is INSERTED on a specific table, verify the first caracter of a nvarchar on the column named "idCli", and depending on their value, call one specific stored procedure that will execute some data modifications to fit on other table on a diferent database.
Each client of mine can have only one table that start the trigger on APP1, but can have many instances of SQL for different codes.
Until now, what we do is:
Find how many different databases (and their names) a specific client have to APP2 and write a specific stored procedure for each database, using the names (that are always different...). We use a template of course, but this don't change the fact the we must correct many times the database name on the different stored procedures.
This increse the time and chance of errors on installing the system.
The first way we think for solve this question is using dinamic sql, like this code:
Code Snippet
CREATE TRIGGER T01
ON [dbo].[table1]
FOR INSERT, UPDATE
AS
-- some code that put values in @v1 and @V2...
IF @v1 = 1
EXEC fct ('DB1..Tabela1', @V2)
ELSE
EXEC fct ('DB2..Tabela1', @V2)
GO
CREATE PROCEDURE fct (@table_name nvarchar(50), @valor int)
AS
EXEC ('INSERT INTO '+@table_name+' (valor) VALUES ('+@valor+')')
GO
This type of code has the advantege (we think) to permit us change only the TRIGGER, and use always the same number of procedures on install.
Is there any security problem to do this type of code?
Even if the @table_name and @valor are determined by the program?
In case of yes, how can I do something like this, or, if this is not possible, how can I "automate" the creation of the procedures with a variable number of choices (like 2 different tables for client A, 5 for client B, etc)?
Thanks in advance
View 8 Replies
View Related
Mar 23, 2006
I want to use parameters within a stored procedure to generate dynamic columns using SUSER_SNAME as the name for the column that I want to dynaically select (e.g. Select @SUSER_SNAME, First, Last, City FROM MyTable). I have been able to successfully use parameters in the WHERE clause within a stored procedure but haven't been able to find a way to use parameters for column names let alone to tie the parameter value back to SUSER_SNAME.
Any insight would be greatly appreciated!
View 4 Replies
View Related
May 7, 2004
Hi, all:
Kind of new to reporting services. I've been playing around with SQL Reporting Services and was wondering if anyone knows how to populate the fields from a dataset in the Report Designer from a stored procedure that uses dynamic SQL. I've had success with non-dynamic stored procedures and inline queries, but am unable to generate fields when the sp contains dynamic SQL. I've tried defining the fields manually, but when I execute the report I receive errors that the fields are undefined.
Any help would be greatly appreciated!
Thanks
View 2 Replies
View Related
Oct 17, 2007
Hello,
I was in a confusion that is Stored Procedures are really fast ? I have a .NET application where I am using Stored Procedures. But recently I cam through this link http://weblogs.asp.net/fbouma/archive/2003/11/18/38178.aspx which describes Stored Procedures are bad and it won't give any performance difference. What is the truth ? Will it give good performance that passing query from the application ?
Please make it clear
View 8 Replies
View Related
Jun 29, 2015
The requirement is create a sql script(1 proc or cursor) which will create multiple procedures dynamically.
Table A
Col1Â
Col2
A
Alpha
For Example: If table A has 3 rows(distinct) so 3 procedures will be created dynamically.
Result:Â
1 PROC_A_ALPHA
2Â PROC_B_BETA
3Â PROC_C_charlie
View 6 Replies
View Related
Mar 12, 2008
Im reviewing my stored procedures for a new application and got to thinking about protecting against sql injection. I think im pretty safe since im using stored procedures and none of them use any 'exec' commands within them, but im not sure.
I was reading this article, and again all the examples that list a stored procedure, have an 'exec' command somewhere that is the culprit. So, in my case lets say I was doing something like this:
Im generally using regularexpression validation controls on the client side of the application and limiting the max length of the input there as well.
Am I safe, or do I need further input checking within the procedure ?
Code Snippet
CREATE PROCEDURE [dbo].[get_Uploads]
@app varchar(50)
--Init variables
SET @error_number = 0
BEGIN TRY
SELECT [Logid],[Filename],[Label],[UploadDate],[App]
FROM UploadLog au
WHERE [App]=@app
END TRY
BEGIN CATCH
SET @error_number = -2
END CATCH
View 1 Replies
View Related
Feb 11, 2015
i am inserting something into the temp table even without creating it before. But this does not give any compilation error. Only when I want to execute the stored procedure I get the error message that there is an invalid temp table. Should this not result in a compilation error rather during the execution time.?
--create the procedure and insert into the temp table without creating it.
--no compilation error.
CREATE PROC testTemp
AS
BEGIN
INSERT INTO #tmp(dt)
SELECT GETDATE()
END
only on calling the proc does this give an execution error
View 3 Replies
View Related
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
Mar 2, 2005
Hi--
I am new to T-SQL i got this code from some website but its not working can anyone let me know why
@cur_tab_name varchar(30) is not decleared while i have decleared
I want to use this for dynamic name of the table.
Thanks.
create table temp_tab
(
tab_name varchar(30),
no_of_rows INTEGER,
)
DECLARE
curREVIEW
CURSOR FOR
select name
from sysobjects
where xtype = 'U'
DECLARE @cur_tab_name varchar(30)
OPEN curREVIEW
FETCH curREVIEW INTO @cur_tab_name
WHILE (@@FETCH_STATUS =0)
BEGIN
DECLARE @count integer
select @count = count(*) from @cur_tab_name
INSERT INTO temp_tab
(@cur_tab_name, @count)
FETCH curREVIEW INTO @cur_tab_name
END
CLOSE curREVIEW
DEALLOCATE curREVIEW
View 1 Replies
View Related
May 16, 2007
Hi..,
I want to know how to create a DTS for dynamic tables..,
Details:
1)I have some tables which created every month(Like [Name][2 char of month][2 char of year] eg: name0206 this table is for feburary 2006),i want to create dts for those tables
View 3 Replies
View Related
Jan 13, 2007
I need to get the field values of a table (name will be dynamic).Then assign those values to properties in a class.Let's say I will get the table name dynamically.dim tblName as string = "tablea"The 2 tables can each have 25 fields or so.I need a way to select the amt and email field values from tblName. Without saying "select job_amt, job_email from ...Is there someway to get the values based on the column name. So if the column name has amt and email, then give me those values.Maybe loop through the datatable - then for each column -- if col.ColumnName.IndexOf("Amt") = 0 or col.ColumnName.IndexOf("email") = 0 thenthen drop that column from the datatable.ex of table structure<u>tablea</u>job_idjob_amtjob_email<u>tableb</u>dance_idamt_dancedance_email
View 3 Replies
View Related
Apr 19, 2007
Hi,I'm trying to create some tables dynamically based on the content of another table in the same database. I found a post that does what I want to do, but I can't get my code (that is similar to the post) to work.Given below is my code: 1 DECLARE @deptCode varchar(50), @numberOfDept int, @tableName varchar(MAX), @columnName varchar(MAX)
2 DECLARE @lengthDeptCode int, @lengthTableName int, @lengthColumnName int
3
4 SELECT @numberOfDept = COUNT(DISTINCT DeptCode)
5 FROM tbl_Department;
6
7 WHILE (@numberOfDept >=0)
8 BEGIN
9 SELECT @deptCode = DeptCode, @lengthDeptCode = LEN(DeptCode)
10 FROM tbl_Department;
11
12 SET @tableName = 'tbl_ProjectNumber'+@deptCode
13 SET @lengthTableName = LEN(@tableName)
14 SET @columnName = 'ProjectNumber'+@deptCode
15 SET @lengthColumnName = LEN(@columnName)
16
17 CREATE TABLE CAST(@tableName as char(@lengthTableName))
18 (
19 CAST(@columnName as char(@lengthColumnName)) int IDENTITY(1,1) NOT NULL
20 )
21
22 SET @numberOfDept = @numberOfDept - 1
23 END
This is actually my first time using SQL programatically so I'm guessing there are alot of problems with it. I just don't know what exactly. The error I get is:Msg 102, Level 15, State 1, Line 18Incorrect syntax near '@tableName'. Thanks.
View 1 Replies
View Related
Jun 19, 2007
Hi there,I am trying to generate tables names on the fly depending on another table. So i am creating a local variable containing the table names as required. I am storing the tables in a local variable called@TABLENAME VARCHAR(16)and when i say SELECT * FROM @TABLENAMEit is giving me an error and I think I cannot declare @TABLENAME as a table variable because I do not want to create a temp table of sorts.I hope I am clear.thanks,Murthy here
View 6 Replies
View Related
Jun 17, 2008
I'm trying to work on an Integration Services project, and want to have a table copied into another table, but this destination table needs a datetimestamp in the name, like tbl061708547pm.
I can get this to work, but if I try to use it with an into statement and a "+", I get an error telling me something is wrong around the "+":
DECLARE @Date char(23)SET @Date = 'myTBL_' + CONVERT(char(23), GETDATE(), 14)SELECT colA, @Date FROM myTBL
*****Error with:DECLARE @Date char(23)SET @Date = 'myTBL_' + CONVERT(char(23), GETDATE(), 14)SELECT * into @Date FROM myTBL
...and error with:DECLARE @Date char(23)SET @Date = CONVERT(char(23), GETDATE(), 14)SELECT * into 'myTBL_ + @Date FROM myTBL;
View 2 Replies
View Related
Aug 23, 2004
Hello, all. I'm attempting to insert data into a table variable using dynamic SQL created at runtime.
However, with a Table variable, SQL server will not allow the EXEC method to be used in an INSERT statement.
How do I go about this?
View 2 Replies
View Related
Jun 22, 2001
Hi There,
I am trying to write dynamic sql which will insert a row into a table.
However, I cannot seem to get the syntax correct.
I will be passing the name of one of the fields to be added and the value
for that field.
If anyone has any suggestions, they would be appreciated.
CREATE PROCEDURE dbo.Add_Daily_Activity_Stats(
@Field_NameVARCHAR(25),
@Team_IdINTEGER,
@TotalINTEGER
)
AS
EXEC ("INSERT INTO Daily_Activity_Stats
(
Date,
Team_Id,
'+@Field_Name+'
)
VALUES
(
GETDATE(),
@Team_Id,
@Total
)
)"
View 3 Replies
View Related
Sep 26, 2001
Is it possible to create a temp table using exec. e.g
exec('create table #temp1 (xyz int, abc int)')
when I run the above statement, I dont get an error but nothing happens.
The reason I need to create it dynamically is that in my stored proc, I am passed a number. This number determines how many columns my temp table should have.
thanks
Zoey
View 2 Replies
View Related
Sep 22, 2000
Does anyone know if it is possible to create dynamically named tables from within a stored procedure? The goal is to append a unique identifier on the end of an otherwise static table name to allow for multiple incarnations of the table to exist concurrently while not interfering with each other. For example, we would like to create and use a temp table that is suffixed with a login name to or a timestamp to make it unique.
Is this possible?
View 6 Replies
View Related
May 19, 2005
Does TSQL limits us on creating temp table using dynamic sql? If so any workaround... Here's the sample code that doesn't let me run second exec because it looks like first exec is not able to create a temp table.
declare @str1 varchar(80),@str2 varchar(80)
set @str1='create table #tmp(col1 int)'
set @str2='insert into #tmp values (10)'
exec (@str1)
exec (@str2)
View 2 Replies
View Related
Oct 13, 2005
The following dynamic SQL script works for creating a table on the fly but if I change the select @tmpTblNm = 'tmpABC' to select @tmpTblNm = '#tmpABC'
it will not create the temp table. Can anyone help on creating a temp table dynamiclly?
declare @tmpTblNm varchar(40),
@str varchar(1000)
select @tmpTblNm = 'tmpABC'
select @str = ''
-- Create a temp table to hold the current page of data
-- Add an ID column to track the current row
select @str = 'Create Table '+ @tmpTblNm +
' ( row_id int IDENTITY PRIMARY KEY,
customerID int,
customerName varchar(40),
address1 varchar(40),
city varchar(25) )'
exec (@str)
View 1 Replies
View Related
Mar 19, 2004
Suppose I have a table named table1 which has a field question_Id.There are many values for this field say 100,101,102.
Now I want to make a table with the field name 100,101,102 but the problem is that it is not fixed how many values are there for question_id.Here in this example I mentioned three(100,101,102) but it may be anything.How can I make a table with the field names this way?
Subhasish
View 3 Replies
View Related
Sep 25, 2015
I've got an update statement with a subquery (I'll post the code further down) that I need to either make dynamic or do something else to make sure it does what I want.
The query is as follows:-
UPDATE dbo.tbl_Process_List_Control_Table
SET LastUpdateDateTime = (
SELECT ISNULL(MAX([LatestRowUpdateDateTime]), @LastUpdateDateTime)
FROM [wtbl_Process_List_Patient]
)
WHERE ProcessList = @ProcessName
This is a called proc with the following parameters:-
@LastUpdateDateTime is the date of the last record to be loaded
@ProcessName is the name of the process that was started/finished.
I need to make [wtbl_Process_List_Patient] dynamic so it looks at a different table based on a passed parameter.I've tried making the whole thing dynamic but it states I need to declare @LastUpdateDateTime which I can't see how to do as it's already passed to the proc (as is the process name).
View 6 Replies
View Related
Jun 5, 2008
Hi all,
I have been attempting to construct some dynamic SQL using a table name as a parameter, and call it using sp_executesql, in SQL Server 2005.
According to all of the searches and articles I have read today, the following should work:
DECLARE @rownumINT
DECLARE @tabNamNVARCHAR(100)
DECLARE @SQLStringNVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
SET @rownum = 35
SET @tabNam = 'AdminScriptHistory'
SELECT @SQLString = N'SELECT * FROM @table where executionorder=@row'
SET @ParmDefinition = N'@table VARCHAR(100), @row INT'
EXEC sp_executesql @SQLString, @ParmDefinition, @tabNam,@rownum
However, it fails with:
Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "@table".
Anybody know why?
Cheers
View 1 Replies
View Related
Jun 17, 2008
I'm trying to work on an Integration Services project, and want to have a table copied into another table, but this destination table needs a datetimestamp in the name, like tbl061708547pm.
I can get this to work, but if I try to use it with an into statement and a "+", I get an error telling me something is wrong around the "+":
DECLARE @Date char(23)
SET @Date = 'myTBL_' + CONVERT(char(23), GETDATE(), 14)
SELECT colA, @Date FROM myTBL
*****
Error with:
DECLARE @Date char(23)
SET @Date = 'myTBL_' + CONVERT(char(23), GETDATE(), 14)
SELECT * into @Date FROM myTBL
...and error with:
DECLARE @Date char(23)
SET @Date = CONVERT(char(23), GETDATE(), 14)
SELECT * into 'myTBL_ + @Date FROM myTBL;
View 3 Replies
View Related
Jan 24, 2007
Hi
I am trying to use sql injection to create a dynamic drop table statment. I have tried to reformat a bunch of ways but can not get it. What am I doing wrong?
set @sql = 'if exists (select * from dbo.sysobjects where id = object_id(N' + @@tblname + ') and OBJECTPROPERTY(id, N' + 'IsUserTable' + ') = 1)'
drop table @@tblname
execute(@sql)
View 2 Replies
View Related