使用简单的sql查询从两个表中选择数据

时间:2016-01-11 06:58:08

标签: sql .net sql-server tsql

如果我有以下查询

if not exists(select * from DeliveryTemplate where TemplateId=2)
                begin                                       
                    select usersCode, 1,2,'User {UsersCode}',' hello {Username},', null 
                    from User
                end

如何扩展此查询以便从DeliveryCode表中再选择一列DeliveryTemplate

4 个答案:

答案 0 :(得分:1)

所以你需要使用"15-09-2016"之类的东西:

JOIN

答案 1 :(得分:0)

declare @count int
declare @DeliveryCode nvarchar(100)
select @count = count(*), 
       @DeliveryCode = DeliveryCode 
       from DeliveryTemplate 
       where TemplateId=2

if @count = 0 
begin                                       
 select usersCode, 
        1, 
        2,
        'User {UsersCode}', 
        'hello {Username},',
        null,
       @DeliveryCode AS 'DeliveryCode'
       from User
end

答案 2 :(得分:0)

这应该通过INNER JOIN进行如下操作:

SELECT usersCode, 1,2,'User {UsersCode}',' hello {Username},', null, DeliveryCode
FROM User 
INNER JOIN DeliveryTemplate ON User.ID=DeliveryTemplate.UserId 
WHERE TemplateId=2 

答案 3 :(得分:0)

if not exists(select * from DeliveryTemplate where TemplateId=2)
            begin                                       
              select usersCode, 1,2,'User {UsersCode}',' hello {Username},', null, DeliveryCode
              from User AS u
              INNER JOIN DeliveryTemplate AS d
              ON u.ID = d.UserID
            end