插入

时间:2016-10-31 14:15:00

标签: sql sql-server tsql

我有一个存储过程插入到包含两个值idusername的表中。 id字段是自动压缩的,因此我的存储过程如下所示:

CREATE PROCEDURE [dbo].[sp_test]
    @username varchar(50)
AS 
BEGIN
    INSERT INTO dbo.testtable(username)
        SELECT
            @username
        FROM 
            tbl.test2
        WHERE 
            username IS NOT NULL

即使没有明确说明,我怎样才能返回id?我尝试了SCOPE_IDENTITY();关键字,但我收到空白和空值。

2 个答案:

答案 0 :(得分:3)

猜测你想要什么,我认为这会更像是这样。

import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Write{
    static JButton button;
    static JTextField one;
    static JTextField two;
    public static void main(String[] args){
        JFrame frame = new JFrame("test");
        one = new JTextField(20);
        two = new JTextField(20);
        button = new JButton("write file");
        button.addActionListener(new ButtonListener());
        JPanel mainPanel = new JPanel();
        mainPanel.add(one);
        mainPanel.add(two);
        mainPanel.add(button);
        frame.getContentPane().add(mainPanel);
        frame.setSize(300,400);
        frame.setVisible(true);
    }
    public static class ButtonListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            try{
            File file = new File("test.txt");
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            String content = one.getText() + " " + two.getText();
            bw.write(content);
            bw.close();
            System.out.println("Done");
            } catch (Exception ex){ex.printStackTrace();}
        }
    }
}

答案 1 :(得分:3)

如果你真的从表中插入了几行,你可以这样得到id:

INSERT INTO dbo.testtable(username)
output inserted.id
SELECT username
FROM dbo.test2
where username is not null