我们在db中已经有了这个表(IPConfig
)。 (Sql Server 2k8)
IP | Member
-----------------------
10.1.2.100 | Joe
10.2.2.200 | Maley
现在,我应该有一个查询,应该这样做:
我从这开始,但无法继续。
IF (NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'IPConfig'))
BEGIN
CREATE TABLE dbo.IPConfig (
IP CHAR(10) PRIMARY KEY NOT NULL,
Member VARCHAR(32) NOT NULL)
END
DECLARE @TempTable Table( -- Create a temp table.
IP CHAR(10) PRIMARY KEY NOT NULL,
Member VARCHAR(32) NOT NULL)
INSERT INTO @TempTable(
IP,
Member)
SELECT
'10.1.2.100', --Already existing Ip; dont insert
'Joe'
UNION SELECT
'10.2.2.200', --Already existing Ip; dont insert
'Maley',
UNION SELECT
'10.3.5.200', --New; Insert.
'NewUser',
UPDATE TABLE dbo.IPConfig
/// Here what should be done ? Should I loop through the temp table using triggers or what is the best way ?
请一个非常简单的例子。
对不起,如果这是一个天真的问题;对MSSQL编程完全陌生。
答案 0 :(得分:4)
如果我理解正确,您只需将新的不匹配的IP插入dbo.IPConfig。左外连接是这里的最佳选择。将结果插入目标表。
INSERT INTO dbo.IPConfig([IP], [Member])
SELECT a.[IP], a.[Member]
FROM @TempTable a
LEFT OUTER JOIN dbo.IPConfig b ON a.[IP]=b.[IP]
WHERE b.[IP] is null
答案 1 :(得分:0)
您不需要任何临时表,但您可以创建存储过程。最简单的方法在这里描述INSERT VALUES WHERE NOT EXISTS
INSERT IPConfig (IP, Member)
SELECT '10.1.2.100', 'Joe'
WHERE NOT EXISTS
( SELECT 1
FROM IPConfig
WHERE IP = '10.1.2.100'
);
作为存储过程:
CREATE PROCEDURE InsertIfNotExist
@IP nvarchar(50),
@Member nvarchar(50)
AS
INSERT IPConfig (IP, Member)
SELECT @IP, @Member
WHERE NOT EXISTS
( SELECT 1
FROM IPConfig
WHERE IP = @IP
);
GO
EXECUTE InsertIfNotExist '10.1.2.100', 'Joe';
EXECUTE InsertIfNotExist '10.2.2.200', 'Maley'