Click to See Complete Forum and Search --> : Use variables to create sql string...


hogmahub
December 4th, 2003, 08:22 AM
Is it possible to drop a variable into a SQL string? Reason being I want to change the fields in the SQL statement based on other factors. I've got this far, but unfortunately it comes up with an error saying that metric isn't a field name (it is though!). If I put it in quotes it returns the value 'metric' in the field


DECLARE @au_lname varchar(40), @au_fname varchar(20), @holder as varchar, @data as varchar(50)


set @holder = metric

DECLARE updated_cursor CURSOR FOR


select SKU, customergroupid, @holder from bp_data where last_update >= (getdate() - 7)

Any help gratefully received.

Ian

hogmahub
December 4th, 2003, 08:24 AM
Should have mentioned I'm trying to do this within a SQL Stored Proc.

Ian

kimmckenzie
December 8th, 2003, 03:41 PM
This is a sample of a stored procedure that recieves a table name as a parameter. You can adjust it for field name.

CREATE PROCEDURE spi_Test
@vTableName varchar
AS
DECLARE @sSQL VarChar(1000)


Select @sSQL = 'SELECT * FROM ' + @vTableName

Exec (@sSQL)

GO