我非常感谢您对以下问题的帮助;我需要创建一个存储过程,它接受两个参数:
@TableName
@KeyField
我需要将它们存储到1个变量中,其中值由|
例如,Customers表如下;
CustomerID CustomerName City
111 Adventure Boston
222 Pubs NY
我执行EXEC mysp 'Customers', 111
我需要返回以下结果格式:
@ReturnValue = 111|Adventure|Boston
这是我的存储过程;
CREATE PROCEDURE my sp
@table varchar
@key numeric
AS
@field varchar(40),
@object int
Select @object = object_id from systables where name =@table
--The instructions to create a cursor
WHILE (@@FETCH_STATUS = 0 )
Select @object = name from sys.columns where object_id = @object
--The instructions to close and deallocate the cursor
--I have already to save the value using the EXEC command but is not working; something like
@String = Select @object from @table where CustomerID = @keyValue
你能帮我吗,
谢谢
答案 0 :(得分:0)
我同意jesuraja你需要将关键列的名称作为参数...如果你可以忍受,你可以尝试这样的事情......
declare @tablename nvarchar(max) = 'Customers'
declare @keyfieldName nvarchar(max) = 'CustomerId'
declare @keyfieldValue int = 111
declare @sql nvarchar(max)
set @sql = convert(nvarchar(max),
(select (select 'isnull(convert(nvarchar(max), ' + c.name + '), '''') + '' | '' + ')
from sys.columns c join sys.tables t on c.object_id = t.object_id
where t.name = @tablename for xml path('')))
set @sql = 'SELECT ' + SUBSTRING(@sql, 1, len(@sql) - 9) + ' FROM ' + @tablename +
' WHERE ' + @keyfieldName + ' = @keyfieldValue'
exec sp_executesql @sql, N'@keyfieldValue as int', @keyfieldValue