How can I make this stored procedure concept work:
---------------
Create Procedure MyProc @.MyValue varchar(5)
As
Declare @.ColumnName as varchar(11)
Set @.ColumnName = 'Price_' + @.MyValue
Select Sum(Price) As @.ColumnName --??
From MyTable where Item = @.MyValue
Return
---------------
Using @.MyValue = 23 should make the Sum(Price) column name 'Price_23'. It's not working. What am I doing wrong?
BjornUSE Northwind
GO
DECLARE @.ColumnName sysname, @.sql varchar(8000), @.myValue varchar(5)
SELECT @.myValue = '23'
SET @.ColumnName = 'Price_' + @.MyValue
SELECT @.sql = 'SELECT Sum(UnitPrice) As ' + @.ColumnName
+ ' FROM [Order Details] '
+ ' WHERE ProductID = ' + @.MyValue
SELECT @.sql
EXEC(@.sql)|||Thank you thank you!
Bjornsql
Showing posts with label columnname. Show all posts
Showing posts with label columnname. Show all posts
Wednesday, March 21, 2012
Sunday, February 19, 2012
Dynamic columnName
Howdy all,
I'm trying to create a sproc that has the column name and search text as input parameters with dynamic SQL... what I have is:
-- Create a variable @.SQLStatement
DECLARE @.SQLStatement varchar(255)
SELECT @.SQLStatement = 'SELECT * FROM myTable WHERE (''' + @.ColumnName + ''' = ''' + @.SearchText + ''')'
-- Execute the SQL statement
EXEC(@.SQLStatement)
The procedure works (at least in Query Analyzer, once I declare/set @.columnname and @.searchtext) in that I don't get any errors. But it returns a blank table with "0 rows affected". However, if I hardcode the variables, it returns the proper data. What's wrong with my select statement??
Thanks!!
JP
SET @.SQLStatement = 'SELECT * FROM myTable WHERE (' + @.ColumnName + ' = ''' + @.SearchText + ''')'
-- Execute the SQL statement
EXEC(@.SQLStatement)|||That's it! Thanks, ndinakar. Those darn quotes...
Subscribe to:
Posts (Atom)