July 26, 2005 at 10:09 am
I have a table (n), the table n keeps string SQL statement:
CREATE TABLE N (
ID INT,
strSQL VARCHAR (1000)
)
the table n is:
cols: id strSQL
row1: 1 select * from @tablename
declare @sql varchar (1000)
declare @tablename varchar (50)
set @tablename = 'a'
SELECT @sql = strSQL from n where id = 1
print @sql (result is : select * from @tablename)
exec (@SQL)
of course I have an error.....
My question is:
how can I execute the string with the parameter @tablename directly. without build the string?
Anyone have some suggestions?
July 26, 2005 at 10:30 am
I have no idea why you would be writing code like this, but the replace function works well here.
CREATE TABLE N (
ID INT,
strSQL VARCHAR (1000)
)
insert into N (id, strsql)
select 1, ' select * from @tablename'
declare @sql varchar (1000)
declare @tablename varchar (50)
set @tablename = 'a'
SELECT @sql = replace(strSQL,'@tableName', @tablename) from n where id = 1
print @sql
July 26, 2005 at 10:31 am
I said what U said.
July 26, 2005 at 10:32 am
I am in shock!!! These are unbelievable close answers
* Noel
July 27, 2005 at 3:17 am
Thank to everybody...for your suggestion.
I thought that someone asked "What a strange question !"
There is a reason but it is too long explain ....just some words.....
I'm building a long procedure which make some operation on all tables of a large DB, but the name of these tables are kept in a catalog table, that, also, keeps (in a column) the operation to do (the operation is SQL statement...depending on the table).
Thank again
July 27, 2005 at 9:10 am
I sould like to do somethng similar - but within the WHERE clause of a stored procedure. I need to pass in a list of ID's as a parameter - then use them in the WHERE and cannot seem to figure out how. Someihting like
CREATE PROCEDURE dbo.p_ExampleProc
(
@List varchar(100) -- contains '(1,2,3)'
@Value int
)
AS
UPDATE TableX
SET SomeColumn = @Value
WHERE ID IN (@List)
Thanks for any helpfule ideas
July 27, 2005 at 9:41 am
A long article about what your trying to do.
http://www.sommarskog.se/arrays-in-sql.html
2 ways to do it.
Create a function that performs some sort parsing of the string.
So like
UPDATE TableX
SET SomeColumn = @Value
WHERE ID IN (select number from uf_returnNumberFromString(@List))
or dynamic sql which has plenty of other issues
declare @sql nvarchar (1000)
set @sql = 'UPDATE TableX
SET SomeColumn = ' + ltrim(Str(@Value)) + '
WHERE ID IN (' + @List+ ')'
exec @sql
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply