Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
velliraj
Yak Posting Veteran
59 Posts |
Posted - 2010-06-29 : 09:34:44
|
| Hi Please help me to create a function to pass the input values as Table name and column of that table.Should return the coulmn valuesplease help |
|
|
vaibhavktiwari83
Aged Yak Warrior
843 Posts |
Posted - 2010-06-29 : 09:36:45
|
| What do you mean by column values on the basis of table name and column name.I mean value of which row you want to return ?Vaibhav TTo walk FAST walk ALONE To walk FAR walk TOGETHER |
 |
|
|
velliraj
Yak Posting Veteran
59 Posts |
Posted - 2010-06-29 : 09:41:25
|
| hi vaibhav,This is like select empid from employeenow im pasing the function input as dbo.employee,empidI need the result of the empidthis should work for any tablehope you have the idea now |
 |
|
|
velliraj
Yak Posting Veteran
59 Posts |
Posted - 2010-06-29 : 09:49:15
|
| DECLARE @colName VARCHAR(500), @colValue VARCHAR(500), @tblName VARCHAR(500), @sql VARCHAR(MAX)SET @colName = 'consultant_ssn'SET @tblName = 'consultants'SET @sql = 'select ' + @colName + ' from ' + @tblName EXEC ( @sql ) |
 |
|
|
vaibhavktiwari83
Aged Yak Warrior
843 Posts |
Posted - 2010-06-29 : 09:57:20
|
For this you need to write stored procedure instead of functionas function doesnot return result set.try this - CREATE Procedure GetColumnData (@TableName AS VARCHAR(100),@ColumnName AS VARCHAR(100))ASBEGIN DECLARE @SQL AS VARCHAR(1000) SELECT @SQL = '' IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE Table_Name = @TableName AND Column_Name = @ColumnName ) BEGIN SET @SQL = 'SELECT ' + @ColumnName + ' FROM ' + @TableName EXEC ( @SQL ) END ELSE BEGIN PRINT 'Invalid table or column name' END ENDGOEXEC GetColumnData 'tablename', 'columnname' Vaibhav TTo walk FAST walk ALONE To walk FAR walk TOGETHER |
 |
|
|
velliraj
Yak Posting Veteran
59 Posts |
Posted - 2010-06-29 : 10:07:33
|
yes i got it.thanks vaibhav for your quick response |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2010-06-29 : 10:10:34
|
| Make sure you read this fullywww.sommarskog.se/dynamic_sql.htmlMadhivananFailing to plan is Planning to fail |
 |
|
|
|
|
|