内部加入2个不同的数据库

时间:2015-10-23 11:09:33

标签: sql sql-server

我可以使用以下查询来连接同一服务器的不同数据库的2个表。 另请告诉我在哪个数据库中执行此查询。

SELECT ...
FROM A.table t1
  JOIN B.table2 t2 ON t2.column = t1.col

1 个答案:

答案 0 :(得分:5)

您只需稍微更改该查询

public interface IExcelWorksheetAdapter
{
    //todo: implement this method, here you have everything you need for an image file
    void AddPicture(FileSystemItem aFile);
}

public class FileSystemItem
{
    public virtual string FullPath { get; protected set; }
    public virtual int Level { get; set; }
    public virtual string Name
    {
        get
        {
            if (string.IsNullOrWhiteSpace(FullPath)) return string.Empty;
            return FullPath.Split('\\').Last();
        }
    }

    public virtual void Operation(IExcelWorksheetAdapter ws) { }
}

public class FolderItem : FileSystemItem
{
    public FolderItem(string fullPath)
    {
        Items = new List<FileSystemItem>();
        if (!Directory.Exists(fullPath)) return;

        FullPath = fullPath;

        var files = Directory.GetFiles(FullPath).Select(p => new FileItem(p) { Level = this.Level + 1 }).ToList();
        Items.AddRange(files);

        var subFolders = Directory.GetDirectories(fullPath).Select(p => new FolderItem(p) {Level = this.Level + 1}).ToList();
        Items.AddRange(subFolders);
    }

    public List<FileSystemItem> Items { get; set; }

    public override void Operation(IExcelWorksheetAdapter ws)
    {
        Items.ForEach(x => x.Operation(ws));
    }
}

public class FileItem : FileSystemItem
{
    public FileItem(string path)
    {
        if (File.Exists(path))
        {
            FullPath = path;
        }
    }

    public override void Operation(IExcelWorksheetAdapter ws)
    {
        ws.AddPicture(this);
    }
}

[TestFixture]
public class DirectoryCompositeTest
{
    [Test]
    public void Operation_for_a_directory_files()
    {
        var directory = new FolderItem(AppDomain.CurrentDomain.BaseDirectory);
        directory.Operation(new Sample()); // give your IExcelWorksheetAdapter implementation here.

    }
}

public class Sample : IExcelWorksheetAdapter
{
    public void AddPicture(FileSystemItem aFile)
    {
        Console.WriteLine(Indent(aFile.Level) + aFile.Name);
    }

    private string Indent(int level)
    {
        string result = "";
        for (int i = 0; i < level; i++)
        {
            result += "-";
        }
        return result;
    }
}

Select * from Database1.[dbo].Table1 tab1
join Database2.[dbo].Table2 tab2 on tab1.ID = tab2.ID

更改数据库,表格和ID的名称并开始使用

您可以在服务器(每个数据库)的所有连接中使用它,因为您的查询引用了数据库