Announcement

Collapse
No announcement yet.

Wie wird dynamisches SQL richtig verwendet...?

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Wie wird dynamisches SQL richtig verwendet...?

    Hallo,
    mit dieser Frage beschäftige ich mich nun schon längere Zeit.
    Ich möchte eine Tabelle für Steuerungszwecke auslesen, und mir aus den Parametern einen dynamischen SQL bauen. Um das ganze zu testen, habe ich folgende prozedur geschrieben, bekomme sie aber einfach nicht zum laufen.
    Wer kann mir helfen ?

    Gruß canacru
    (Canada Cruiser)

    DECLARE @table NVARCHAR(100);
    DECLARE @SQLString NVARCHAR(500);
    DECLARE @path NVARCHAR(100);
    DECLARE @Parm_table NVARCHAR(500);
    DECLARE @Parm_path NVARCHAR(500);
    DECLARE @Int_table NVARCHAR(100);
    DECLARE @Int_path NVARCHAR(100);

    print 'ANFANG'

    /* Build the SQL string one time. */
    SET @SQLString = N'Select * from @table'
    print @SQLString

    /* Specify the parameter format one time. */
    SET @Parm_table = N'@table NVARCHAR(100)'
    SET @table = N'dbo.TEMP_BONUS'
    /* Execute the string with the first parameter value. */
    EXECUTE sp_executesql @SQLString, @Parm_table, @table;


    Dabei kommt dann folgende Fehlermeldung:
    ANFANG
    Select * from @table
    Msg 1087, Level 15, State 2, Line 1
    Must declare the table variable "@table".


    ??? Hab ich doch, oder doch nicht ?

  • #2
    Hallo canacru,

    dynamisches SQL funktioniert so nicht bei Objekt-Namen, das geht nur mit Werten.
    Versuch es mal so:
    [highlight=sql]

    /* Build the SQL string one time. */
    SET @SQLString = N'Select * from '
    print @SQLString

    /* Specify the parameter format one time. */
    SET @table = N'dbo.TEMP_BONUS'
    SET @SQLString = @SQLString + @table
    print @SQLString

    /* Execute the string with the first parameter value. */
    EXECUTE sp_executesql @SQLString
    [/highlight]


    Gruß, Olaf
    Olaf Helper

    <Blog> <Xing>
    * cogito ergo sum * errare humanum est * quote erat demonstrandum *
    Wenn ich denke, ist das ein Fehler und das beweise ich täglich

    Comment


    • #3
      Hallo Olaf,
      es funktioniert so. Vielen Dank für die Hilfe. ich werde diesen Tipp in Zukunft noch häufig anwenden...dann aber auch mit etwas anspruchsvolleren SQL-Abfragen.
      Bis zum nächsten Problem.

      Gruß,
      Wolfgang

      Comment

      Working...
      X