使用变量确定要从中选择的表

时间:2011-12-27 23:11:29

标签: sql sql-server sql-server-2008 procedure

这是我得到的新错误:

IF object_id('Osvezi') IS NULL

EXEC sp_executesql N' 
CREATE PROCEDURE Osvezi
    -- Add the parameters for the stored procedure here
    @tablica nvarchar(200)
AS
BEGIN
   IF @tablica = 'Uporabniki' THEN SELECT * FROM Uporabniki;

   IF @tablica = 'Dokumenti' THEN SELECT * from Dokumenti;
END'
GO

2 个答案:

答案 0 :(得分:0)

你可以这样做,但不推荐

CREATE PROCEDURE Osvezi
    -- Add the parameters for the stored procedure here
    @tablica nvarchar(200)
AS
BEGIN
    EXECUTE('SELECT * FROM' + @tablica);
END

还取决于您使用的是哪个DBMS; SQL SERVER? MYSQL? POSTGRESQL?

修改

如果您需要这种灵活性,请尝试Entity-Attribute-Value Model

答案 1 :(得分:-1)

您需要在字符串中使用双''来获得一个',并且需要删除then

IF object_id('Osvezi') IS NULL
EXEC sp_executesql N' 
CREATE PROCEDURE Osvezi
    -- Add the parameters for the stored procedure here
    @tablica nvarchar(200)
AS
BEGIN
   IF @tablica = ''Uporabniki'' SELECT * FROM Uporabniki;

   IF @tablica = ''Dokumenti'' SELECT * from Dokumenti;
END'
GO